package cn.stylefeng.guns.modular.business.frequency.ordersub.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.exception.enums.StatusExceptionEnum;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.login.SysLoginUser;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.app.mapper.PayOrderConfigMapper;
import cn.stylefeng.guns.modular.business.app.pojo.PayOrderConfig;
import cn.stylefeng.guns.modular.business.app.service.impl.ApiPayServiceImpl;
import cn.stylefeng.guns.modular.business.custom.constant.PublicCommon;
import cn.stylefeng.guns.modular.business.custom.enums.*;
import cn.stylefeng.guns.modular.business.frequency.appmessage.service.AppMessageService;
import cn.stylefeng.guns.modular.business.frequency.banner.config.activityMq.Producer;
import cn.stylefeng.guns.modular.business.frequency.cmarea.entity.CmArea;
import cn.stylefeng.guns.modular.business.frequency.cmarea.mapper.CmAreaMapper;
import cn.stylefeng.guns.modular.business.frequency.cmcity.entity.CmCity;
import cn.stylefeng.guns.modular.business.frequency.cmcity.mapper.CmCityMapper;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.mapper.CmCompanyMapper;
import cn.stylefeng.guns.modular.business.frequency.cmcompanyorder.entity.CmCompanyOrder;
import cn.stylefeng.guns.modular.business.frequency.cmcompanyorder.mapper.CmCompanyOrderMapper;
import cn.stylefeng.guns.modular.business.frequency.cmlinkman.entity.CmLinkman;
import cn.stylefeng.guns.modular.business.frequency.cmlinkman.mapper.CmLinkmanMapper;
import cn.stylefeng.guns.modular.business.frequency.finance.entity.Finance;
import cn.stylefeng.guns.modular.business.frequency.finance.mapper.FinanceMapper;
import cn.stylefeng.guns.modular.business.frequency.finance.service.FinanceService;
import cn.stylefeng.guns.modular.business.frequency.financedetail.entity.FinanceDetail;
import cn.stylefeng.guns.modular.business.frequency.financedetail.mapper.FinanceDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.financesettlement.mapper.FinanceSettlementMapper;
import cn.stylefeng.guns.modular.business.frequency.financetransport.entity.FinanceTransport;
import cn.stylefeng.guns.modular.business.frequency.financetransport.mapper.FinanceTransportMapper;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.mapper.OrderCarVerifyMapper;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.service.OrderCarVerifyService;
import cn.stylefeng.guns.modular.business.frequency.orderextrafee.entity.OrderExtraFee;
import cn.stylefeng.guns.modular.business.frequency.orderextrafee.mapper.OrderExtraFeeMapper;
import cn.stylefeng.guns.modular.business.frequency.orderfinishimage.mapper.OrderFinishImageMapper;
import cn.stylefeng.guns.modular.business.frequency.orderfinishrecord.mapper.OrderFinishRecordMapper;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.entity.OrderLogistics;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.mapper.OrderLogisticsMapper;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.entity.OrderModifyDetail;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.mapper.OrderModifyDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.orderpayrecord.mapper.OrderPayRecordMapper;
import cn.stylefeng.guns.modular.business.frequency.orderpick.entity.OrderPick;
import cn.stylefeng.guns.modular.business.frequency.orderpick.mapper.OrderPickMapper;
import cn.stylefeng.guns.modular.business.frequency.orderroyalty.mapper.OrderRoyaltyMapper;
import cn.stylefeng.guns.modular.business.frequency.orderstock.mapper.OrderStockMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.entity.OrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.enums.OrderSubExceptionEnum;
import cn.stylefeng.guns.modular.business.frequency.ordersub.mapper.OrderSubMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderDTO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderSubParam;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderVO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.*;
import cn.stylefeng.guns.modular.business.frequency.ordersub.service.OrderSubService;
import cn.stylefeng.guns.modular.business.frequency.ordertake.entity.OrderTake;
import cn.stylefeng.guns.modular.business.frequency.ordertake.mapper.OrderTakeMapper;
import cn.stylefeng.guns.modular.business.frequency.settlementbargain.entity.SettlementBargain;
import cn.stylefeng.guns.modular.business.frequency.settlementbargain.service.SettlementBargainService;
import cn.stylefeng.guns.modular.business.frequency.syssite.entity.SysSite;
import cn.stylefeng.guns.modular.business.frequency.syssite.mapper.SysSiteMapper;
import cn.stylefeng.guns.modular.business.frequency.transport.entity.Transport;
import cn.stylefeng.guns.modular.business.frequency.transport.mapper.TransportMapper;
import cn.stylefeng.guns.modular.business.frequency.transportlevel.entity.TransportLevel;
import cn.stylefeng.guns.modular.business.frequency.transportlevel.mapper.TransportLevelMapper;
import cn.stylefeng.guns.modular.business.frequency.transportleveldetail.entity.TransportLevelDetail;
import cn.stylefeng.guns.modular.business.frequency.transportleveldetail.mapper.TransportLevelDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.transportsign.mapper.TransportSignMapper;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.BaseUtils;
import cn.stylefeng.guns.sys.modular.emp.mapper.SysEmpMapper;
import cn.stylefeng.guns.sys.modular.role.RoleConstant;
import cn.stylefeng.guns.sys.modular.user.entity.SysUser;
import cn.stylefeng.guns.sys.modular.user.factory.MD5Ry;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import cn.stylefeng.guns.sys.modular.util.SnowIdUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 子订单 服务实现类
 *
 * @author yujie
 * @date 2023/05/09 17:16
 */

@Slf4j
@Service
public class OrderSubServiceImpl extends ServiceImpl<OrderSubMapper, OrderSub> implements OrderSubService {
    @Autowired
    private BusinessUtil businessUtil;
    @Autowired
    private CmLinkmanMapper linkmanMapper;
    @Resource
    private FinanceService financeService;
    @Autowired
    private Producer producer;
    @Autowired
    private SettlementBargainService settlementBargainService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private OrderSubMapper orderSubMapper;

    @Resource
    private FinanceMapper financeMapper;
    @Resource
    private FinanceDetailMapper financeDetailMapper;

    @Resource
    private CmCompanyMapper companyMapper;
    @Resource
    private CmCompanyOrderMapper companyOrderMapper;
    @Autowired
    private SysUserService sysUserService;
    /*@Resource
    private SysUser userMapper;*/
    @Resource
    private OrderRoyaltyMapper orderRoyaltyMapper;
    @Resource
    private OrderModifyDetailMapper orderModifyDetailMapper;
    @Resource
    private CmCityMapper cmCityMapper;
    @Resource
    private CmAreaMapper cmAreaMapper;
    @Autowired
    private OrderPickMapper pickCarMapper;
    @Resource
    private OrderTakeMapper orderTakeMapper;
    @Resource
    private OrderCarVerifyMapper orderCarVerifyMapper;
    @Resource
    private OrderExtraFeeMapper orderExtraFeeMapper;
    @Resource
    private TransportLevelDetailMapper transportLevelDetailMapper;
    @Resource
    private TransportSignMapper orderSignMapper;
    @Resource
    private OrderStockMapper orderStockMapper;
    @Resource
    private OrderFinishRecordMapper orderFinishRecordMapper;
    @Resource
    private OrderPayRecordMapper orderPayRecordMapper;
    @Resource
    private OrderFinishImageMapper orderFinishImageMapper;
    @Resource
    private OrderLogisticsMapper logisticsMapper;
    @Resource
    private TransportMapper transportMapper;
    @Resource
    private TransportLevelMapper transportLevelMapper;
    @Resource
    private FinanceTransportMapper financeTransportMapper;

    @Resource
    private SysSiteMapper siteMapper;

    @Autowired
    private PayOrderConfigMapper payOrderConfigMapper;


    @Override
    public PageResult<OrderSub> page(OrderSubParam orderSubParam) {

        // 构造条件
        LambdaQueryWrapper<OrderSub> queryWrapper = new LambdaQueryWrapper<>();

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<OrderSub> list(OrderSubParam orderSubParam) {

        // 构造条件
        LambdaQueryWrapper<OrderSub> queryWrapper = new LambdaQueryWrapper<>();

        return this.list(queryWrapper);
    }

    @Override
    public void add(OrderSubParam orderSubParam) {

        // 将dto转为实体
        OrderSub orderSub = new OrderSub();
        BeanUtil.copyProperties(orderSubParam, orderSub);
        this.save(orderSub);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(OrderSubParam orderSubParam) {

        // 根据id查询实体
        OrderSub orderSub = this.queryOrderSub(orderSubParam);

        // 更新实体
        this.updateById(orderSub);

    }

    @Override
    public void edit(OrderSubParam orderSubParam) {

        // 根据id查询实体
        OrderSub orderSub = this.queryOrderSub(orderSubParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(orderSubParam, orderSub);

        // 不能修改状态，用修改状态接口修改状态
        orderSub.setStatus(null);

        this.updateById(orderSub);
    }

    @Override
    public OrderSub detail(OrderSubParam orderSubParam) {
        return this.queryOrderSub(orderSubParam);
    }

    @Override
    public void changeStatus(OrderSubParam orderSubParam) {
        Long id = orderSubParam.getId();
        Integer status = orderSubParam.getStatus();
        // 更新枚举，更新只能更新未删除状态的
        LambdaUpdateWrapper<OrderSub> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(OrderSub::getId, id).set(OrderSub::getStatus, status);
        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new ServiceException(StatusExceptionEnum.UPDATE_STATUS_ERROR);
        }
    }

    @Override
    public boolean checkOrderCreate(OrderVO orderVO, StringBuilder errorMsg) {
        // 订单客户联系人不能为空
        if (orderVO == null || orderVO.getLinkmanId() == null) {
            errorMsg.append("参数错误");
            return false;
        }
        // 车辆信息不能为空
        if (orderVO.getOrderSubList() == null || orderVO.getOrderSubList().size() == 0) {
            errorMsg.append("车辆信息不能为空");
            return false;
        }

        //现付到付欠付月结必须要能够整除
        if (!checkFinanceData(orderVO)) {
            errorMsg.append("财务应收款必须为车辆数量的整数倍, 否则请分开录单");
            return false;
        }

        //运输费不能为空 不能为0
        if (orderVO.getTransportFee() == null || orderVO.getTransportFee().compareTo(BigDecimal.ZERO) != 1) {
            errorMsg.append("运输费必须大于0");
            return false;
        }

        // 拆分每辆车的付款金额
        splitPaymentFee(orderVO);
        return true;

    }

    private void splitPaymentFee(OrderVO orderVO) {
        int needSplit = 0;
        int hasSplit = 0;
        // 计算个子订单保险费之和
        BigDecimal notNeedSplitFee = getTotalInsuranceFee(orderVO);
        if (notNeedSplitFee.compareTo(BigDecimal.ZERO) > 0) {
            needSplit = 1;
        }
        // 到付
        if (orderVO.getDeliveryPayFee() != null) {
            if (needSplit == 1) {
                List<BigDecimal> list = split(orderVO.getDeliveryPayFee().subtract(notNeedSplitFee), orderVO.getOrderSubList().size());
                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                    BigDecimal insuranceFee = orderVO.getOrderSubList().get(i).getInsuranceFee() == null ?
                            BigDecimal.ZERO : orderVO.getOrderSubList().get(i).getInsuranceFee();
                    orderVO.getOrderSubList().get(i).setDeliveryPayFee(list.get(i).add(insuranceFee));
                }
                hasSplit = 1;
            } else {
                List<BigDecimal> list = split(orderVO.getDeliveryPayFee(), orderVO.getOrderSubList().size());
                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                    orderVO.getOrderSubList().get(i).setDeliveryPayFee(list.get(i));
                }
            }
        } else {
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setDeliveryPayFee(BigDecimal.ZERO);
            }
        }
        // 欠付
        if (orderVO.getBackPayFee() != null) {
            if (needSplit == 1 && hasSplit == 0) {
                List<BigDecimal> list = split(orderVO.getBackPayFee().subtract(notNeedSplitFee), orderVO.getOrderSubList().size());
                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                    BigDecimal insuranceFee = orderVO.getOrderSubList().get(i).getInsuranceFee() == null ?
                            BigDecimal.ZERO : orderVO.getOrderSubList().get(i).getInsuranceFee();
                    orderVO.getOrderSubList().get(i).setBackPayFee(list.get(i).add(insuranceFee));
                }
                hasSplit = 1;
            } else {
                List<BigDecimal> list = split(orderVO.getBackPayFee(), orderVO.getOrderSubList().size());
                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                    orderVO.getOrderSubList().get(i).setBackPayFee(list.get(i));
                }
            }
        } else {
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setBackPayFee(BigDecimal.ZERO);
            }
        }
        // 月结
        if (orderVO.getSlotPayFee() != null) {
            if (needSplit == 1 && hasSplit == 0) {
                List<BigDecimal> list = split(orderVO.getSlotPayFee().subtract(notNeedSplitFee), orderVO.getOrderSubList().size());
                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                    BigDecimal insuranceFee = orderVO.getOrderSubList().get(i).getInsuranceFee() == null ?
                            BigDecimal.ZERO : orderVO.getOrderSubList().get(i).getInsuranceFee();
                    orderVO.getOrderSubList().get(i).setSlotPayFee(list.get(i).add(insuranceFee));
                }
                hasSplit = 1;
            } else {
                List<BigDecimal> list = split(orderVO.getSlotPayFee(), orderVO.getOrderSubList().size());
                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                    orderVO.getOrderSubList().get(i).setSlotPayFee(list.get(i));
                }
            }
        } else {
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setSlotPayFee(BigDecimal.ZERO);
            }
        }
        // 现付
        if (orderVO.getSpotPayFee() != null) {
            if (needSplit == 1 && hasSplit == 0) {
                List<BigDecimal> list = split(orderVO.getSpotPayFee().subtract(notNeedSplitFee), orderVO.getOrderSubList().size());
                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                    BigDecimal insuranceFee = orderVO.getOrderSubList().get(i).getInsuranceFee() == null ?
                            BigDecimal.ZERO : orderVO.getOrderSubList().get(i).getInsuranceFee();
                    orderVO.getOrderSubList().get(i).setSpotPayFee(list.get(i).add(insuranceFee));
                }
            } else {
                List<BigDecimal> list = split(orderVO.getSpotPayFee(), orderVO.getOrderSubList().size());
                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                    orderVO.getOrderSubList().get(i).setSpotPayFee(list.get(i));
                }
            }
        } else {
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setSpotPayFee(BigDecimal.ZERO);
            }
        }
        // 提车费
        if (orderVO.getPickFee() != null) {
            List<BigDecimal> list = split(orderVO.getPickFee(), orderVO.getOrderSubList().size());
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setPickFee(list.get(i));
            }
        } else {
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setPickFee(BigDecimal.ZERO);
            }
        }
        // 送车费
        if (orderVO.getTakeFee() != null) {
            List<BigDecimal> list = split(orderVO.getTakeFee(), orderVO.getOrderSubList().size());
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setTakeFee(list.get(i));
            }
        } else {
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setTakeFee(BigDecimal.ZERO);
            }
        }
        // 返款
        if (orderVO.getKickbackFee() != null) {
            List<BigDecimal> list = split(orderVO.getKickbackFee(), orderVO.getOrderSubList().size());
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setKickbackFee(list.get(i));
            }
        } else {
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setKickbackFee(BigDecimal.ZERO);
            }
        }
        // 税费
        if (orderVO.getInvoiceFee() != null) {
            List<BigDecimal> list = split(orderVO.getInvoiceFee(), orderVO.getOrderSubList().size());
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setInvoiceFee(list.get(i));
            }
        } else {
            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
                orderVO.getOrderSubList().get(i).setInvoiceFee(BigDecimal.ZERO);
            }
        }
    }

//    private void splitPaymentFee(OrderVO orderVO) {
//        int needSplit = 0;
//        int hasSplit = 0;
//        // 计算个子订单保险费之和
//        BigDecimal notNeedSplitFee = getTotalInsuranceFee(orderVO);
//        if (notNeedSplitFee.compareTo(BigDecimal.ZERO) > 0) {
//            needSplit = 1;
//        }
//        // 到付
//        if (orderVO.getDeliveryPayFee() != null && orderVO.getDeliveryPayFee().compareTo(BigDecimal.ZERO) > 0) {
//            if (needSplit == 1) {
//                List<BigDecimal> list = split(orderVO.getDeliveryPayFee().subtract(notNeedSplitFee), orderVO.getOrderSubList().size());
//                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                    BigDecimal insuranceFee = orderVO.getOrderSubList().get(i).getInsuranceFee() == null ?
//                            BigDecimal.ZERO : orderVO.getOrderSubList().get(i).getInsuranceFee();
//                    orderVO.getOrderSubList().get(i).setDeliveryPayFee(list.get(i).add(insuranceFee));
//                }
//                hasSplit = 1;
//            } else {
//                List<BigDecimal> list = split(orderVO.getDeliveryPayFee(), orderVO.getOrderSubList().size());
//                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                    orderVO.getOrderSubList().get(i).setDeliveryPayFee(list.get(i));
//                }
//            }
//        } else {
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setDeliveryPayFee(null);
//            }
//        }
//        // 欠付
//        if (orderVO.getBackPayFee() != null && orderVO.getBackPayFee().compareTo(BigDecimal.ZERO) > 0) {
//            if (needSplit == 1 && hasSplit == 0) {
//                List<BigDecimal> list = split(orderVO.getBackPayFee().subtract(notNeedSplitFee), orderVO.getOrderSubList().size());
//                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                    BigDecimal insuranceFee = orderVO.getOrderSubList().get(i).getInsuranceFee() == null ?
//                            BigDecimal.ZERO : orderVO.getOrderSubList().get(i).getInsuranceFee();
//                    orderVO.getOrderSubList().get(i).setBackPayFee(list.get(i).add(insuranceFee));
//                }
//                hasSplit = 1;
//            } else {
//                List<BigDecimal> list = split(orderVO.getBackPayFee(), orderVO.getOrderSubList().size());
//                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                    orderVO.getOrderSubList().get(i).setBackPayFee(list.get(i));
//                }
//            }
//        } else {
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setBackPayFee(null);
//            }
//        }
//        // 月结
//        if (orderVO.getSlotPayFee() != null && orderVO.getSlotPayFee().compareTo(BigDecimal.ZERO) > 0) {
//            if (needSplit == 1 && hasSplit == 0) {
//                List<BigDecimal> list = split(orderVO.getSlotPayFee().subtract(notNeedSplitFee), orderVO.getOrderSubList().size());
//                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                    BigDecimal insuranceFee = orderVO.getOrderSubList().get(i).getInsuranceFee() == null ?
//                            BigDecimal.ZERO : orderVO.getOrderSubList().get(i).getInsuranceFee();
//                    orderVO.getOrderSubList().get(i).setSlotPayFee(list.get(i).add(insuranceFee));
//                }
//                hasSplit = 1;
//            } else {
//                List<BigDecimal> list = split(orderVO.getSlotPayFee(), orderVO.getOrderSubList().size());
//                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                    orderVO.getOrderSubList().get(i).setSlotPayFee(list.get(i));
//                }
//            }
//        } else {
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setSlotPayFee(null);
//            }
//        }
//        // 现付
//        if (orderVO.getSpotPayFee() != null && orderVO.getSpotPayFee().compareTo(BigDecimal.ZERO) > 0) {
//            if (needSplit == 1 && hasSplit == 0) {
//                List<BigDecimal> list = split(orderVO.getSpotPayFee().subtract(notNeedSplitFee), orderVO.getOrderSubList().size());
//                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                    BigDecimal insuranceFee = orderVO.getOrderSubList().get(i).getInsuranceFee() == null ?
//                            BigDecimal.ZERO : orderVO.getOrderSubList().get(i).getInsuranceFee();
//                    orderVO.getOrderSubList().get(i).setSpotPayFee(list.get(i).add(insuranceFee));
//                }
//            } else {
//                List<BigDecimal> list = split(orderVO.getSpotPayFee(), orderVO.getOrderSubList().size());
//                for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                    orderVO.getOrderSubList().get(i).setSpotPayFee(list.get(i));
//                }
//            }
//        } else {
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setSpotPayFee(null);
//            }
//        }
//        // 提车费
//        if (orderVO.getPickFee() != null && orderVO.getPickFee().compareTo(BigDecimal.ZERO) > 0) {
//            List<BigDecimal> list = split(orderVO.getPickFee(), orderVO.getOrderSubList().size());
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setPickFee(list.get(i));
//            }
//        } else {
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setPickFee(null);
//            }
//        }
//        // 送车费
//        if (orderVO.getTakeFee() != null && orderVO.getTakeFee().compareTo(BigDecimal.ZERO) > 0) {
//            List<BigDecimal> list = split(orderVO.getTakeFee(), orderVO.getOrderSubList().size());
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setTakeFee(list.get(i));
//            }
//        } else {
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setTakeFee(null);
//            }
//        }
//        // 返款
//        if (orderVO.getKickbackFee() != null && orderVO.getKickbackFee().compareTo(BigDecimal.ZERO) > 0) {
//            List<BigDecimal> list = split(orderVO.getKickbackFee(), orderVO.getOrderSubList().size());
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setKickbackFee(list.get(i));
//            }
//        } else {
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setKickbackFee(null);
//            }
//        }
//        // 税费
//        if (orderVO.getInvoiceFee() != null && orderVO.getInvoiceFee().compareTo(BigDecimal.ZERO) > 0) {
//            List<BigDecimal> list = split(orderVO.getInvoiceFee(), orderVO.getOrderSubList().size());
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setInvoiceFee(list.get(i));
//            }
//        } else {
//            for (int i = 0; i < orderVO.getOrderSubList().size(); i++) {
//                orderVO.getOrderSubList().get(i).setInvoiceFee(null);
//            }
//        }
//    }


    private static List<BigDecimal> split(BigDecimal total, int count) {
        List<BigDecimal> list = new ArrayList<>(count);
        if (count <= 1) {
            list.add(total);
        } else {
            BigDecimal avg = total.divide(new BigDecimal(count), 0, RoundingMode.DOWN);
            for (int i = 1; i <= count; i++) {
                if (i == count) {
                    BigDecimal endNum = new BigDecimal(i - 1);
                    BigDecimal multiply = avg.multiply(endNum);
                    BigDecimal subtract = total.subtract(multiply);
                    list.add(subtract);
                } else {
                    list.add(avg);
                }
            }
        }
        return list;
    }

    private BigDecimal getTotalInsuranceFee(OrderVO orderVO) {
        BigDecimal total = BigDecimal.ZERO;
        for (OrderSub os : orderVO.getOrderSubList()) {
            if (os.getInsuranceFee() != null) {
                total = total.add(os.getInsuranceFee());
            }
        }
        return total;
    }

    private boolean checkFinanceData(OrderVO orderVO) {
        int scale = orderVO.getOrderSubList().size();
        if (orderVO.getSpotPayFee() != null && orderVO.getSpotPayFee().compareTo(BigDecimal.ZERO) > 0) {
            if (orderVO.getSpotPayFee().longValue() % scale != 0) {
                return false;
            }
        }
        if (orderVO.getDeliveryPayFee() != null && orderVO.getDeliveryPayFee().compareTo(BigDecimal.ZERO) > 0) {
            if (orderVO.getDeliveryPayFee().longValue() % scale != 0) {
                return false;
            }
        }
        if (orderVO.getBackPayFee() != null && orderVO.getBackPayFee().compareTo(BigDecimal.ZERO) > 0) {
            if (orderVO.getBackPayFee().longValue() % scale != 0) {
                return false;
            }
        }
        if (orderVO.getSlotPayFee() != null && orderVO.getSlotPayFee().compareTo(BigDecimal.ZERO) > 0) {
            if (orderVO.getSlotPayFee().longValue() % scale != 0) {
                return false;
            }
        }
        return true;
    }

    @Autowired
    private ApiPayServiceImpl apiPayService;

    @Override
    public ResponseData createOrder(OrderVO orderVO) {
        Long tenantId = businessUtil.getTenantId();
        Long orderId = SnowIdUtils.uniqueLong();
        int index = 1;
        int size = orderVO.getOrderSubList().size();
        String orderNo = businessUtil.getOrderNo(tenantId);

        //创建集合存储订单id
        List<Long> orderList = new ArrayList<>();

        //创建BigDecimal用来保存总的现付金额
        //BigDecimal bigDecimal = new BigDecimal("0");
        System.out.println("628 =" + System.currentTimeMillis());
        //结算人
        addSettlementBargain(orderVO.getConsigneeName(), orderVO.getConsigneePhone(), orderVO.getLinkmanId());
        for (OrderSub os : orderVO.getOrderSubList()) {
            os.setOrderId(orderId);
            os.setUpdateVersion(orderId.toString());
            // 生成子订单号
            os.setOrderSubNo(createOrderSubNo(Long.parseLong(orderNo), size, index));
            // 订单状态
            os.setStatus(orderVO.getPickType() == PickCarTypeEnum.ZI_SONG_WAND_DIAN.type ? OrderStatusEnum.WAIT_PICK.status : OrderStatusEnum.NEW_ORDER.status);
            //carName carCost vin insuranceFee 实体自带，不需要塞值
            os.setPaymentType(Arrays.toString(orderVO.getPaymentType()));
            os.setLinkmanId(orderVO.getLinkmanId());
            os.setTenantId(tenantId);
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(orderVO.getCompanyName())) {
                os.setCompanyName("---");
            } else {
                os.setCompanyName(orderVO.getCompanyName());
            }
            os.setLinkmanName(orderVO.getLinkmanName());
            os.setLinkmanPhone(orderVO.getLinkmanPhone());
            os.setConsigneeName(orderVO.getConsigneeName());
            os.setConsigneePhone(orderVO.getConsigneePhone());
            os.setStartCode(orderVO.getStartCode());
            os.setDestinationCode(orderVO.getDestinationCode());
            os.setPickType(orderVO.getPickType());
            //os.setPickFee(orderVO.getPickFee());
            os.setTakeType(orderVO.getTakeType());
            //os.setTakeFee(orderVO.getTakeFee());
            os.setPickLinkmanName(orderVO.getPickLinkmanName());
            os.setPickLinkmanPhone(orderVO.getPickLinkmanPhone());
            os.setTakeLinkmanName(orderVO.getTakeLinkmanName());
            os.setTakeLinkmanPhone(orderVO.getTakeLinkmanPhone());
            os.setPickAreaCode(orderVO.getPickAreaCode());
            os.setPickAddress(orderVO.getPickAddress());
            os.setTakeAreaCode(orderVO.getTakeAreaCode());
            os.setTakeAddress(orderVO.getTakeAddress());
            os.setHasUrgent(orderVO.getHasUrgent());
            //os.setHasInsurance(orderVO.getHasInsurance());
            os.setAppointPickTime(orderVO.getAppointPickTime());
            os.setRemark(orderVO.getRemark());
            os.setTransportType(orderVO.getTransportType());
            // 费用信息
            // 运费
            os.setTransportFee(orderVO.getTransportFee());
            // 返款
            //os.setKickbackFee(orderVO.getKickbackFee() == null ? BigDecimal.ZERO : orderVO.getKickbackFee().divide(new BigDecimal(size), 0, RoundingMode.HALF_UP));
            // 税额
            //os.setInvoiceFee(orderVO.getInvoiceFee() == null ? BigDecimal.ZERO : orderVO.getInvoiceFee().divide(new BigDecimal(size), 0, RoundingMode.HALF_UP));
            // 总运费
            os.setTotalFee(getOrderSubTotalFee(os));
            // 现付到付欠付月结
            this.save(os);
            System.out.println("681 =" + System.currentTimeMillis());
            // 财务应收基础数据插入
            dealFinanceCollectionData(os, 0, tenantId);
            System.out.println("684 =" + System.currentTimeMillis());
            // 客户订单表数据插入
            addCompanyOrder(os, tenantId);
            System.out.println("687 =" + System.currentTimeMillis());
            // 制单奖金 提成表数据插入
            addOrderBonus(os);
            System.out.println("690 =" + System.currentTimeMillis());
            //添加提醒记录
            addAppMessge(os, orderVO);
            index++;

            //保存订单id
            orderList.add(os.getId());

            //叠加每个订单的现付金额
            /*Integer[] paymentType = orderVO.getPaymentType();
            List<Integer> list = Arrays.asList(paymentType);
            if (list.contains(1)) {
                bigDecimal = bigDecimal.add(os.getSpotPayFee());
            }*/
        }
        // 客户最近下单时间更新 处理
        dualCustomerInfo(orderVO);
        System.out.println("706 =" + System.currentTimeMillis());
        //调用支付接口
        /*PayOrderVO payOrderVO = new PayOrderVO();
        payOrderVO.setOrderIdList(orderList);
        payOrderVO.setPayType(3);

        if ("0".equals(bigDecimal.toString())) {
            //表示没有现付直接返回
            return ResponseData.success();
        }

        payOrderVO.setTransAmt(bigDecimal.toString());
        String payType = orderVO.getPayType();
        if ("1".equals(payType)) {
            payOrderVO.setTradeType("2");
        } else if ("2".equals(payType)) {
            payOrderVO.setTradeType("4");
        } else {
            //先不支付
            return ResponseData.success();
        }
        payOrderVO.setGoodsDesc("现付-线上支付");
        String openId = orderVO.getOpenId();
        if (StringUtils.isNotEmpty(openId)) {
            payOrderVO.setOpenId(openId);
        }*/
        //return apiPayService.createPayOrder(payOrderVO);
        return ResponseData.success(orderList);
    }


    @Resource
    private AppMessageService appMessageService;

    /**
     * 添加提车提醒
     */
    private void addAppMessge(OrderSub os, OrderVO orderVO) {
        if (orderVO.getPickType() == PickCarTypeEnum.ZI_SONG_WAND_DIAN.type) {
            //自提订单   待验车提醒
            log.info("---------------------> 自送订单不添加提车提醒消息  提车方式{}  {}", orderVO.getPickType(), PickCarTypeEnum.getValue(orderVO.getPickType()));
            //自提订单直接进入待验车 创建待验车提醒
            businessUtil.addMessage(String.format("%s  %s待验车提醒", os.getCarName(), os.getVin()), "你有一个待验车订单，请及时处理", os, 2);
            return;
        }
        //非自提订单  待提车提醒
        businessUtil.addMessage(String.format("%s  %s待提车提醒", os.getCarName(), os.getVin()), "你有一个提车待处理订单，请及时处理", os, 1);
    }

    private void addSettlementBargain(String consigneeName, String consigneePhone, Long linkmanId) {
        //添加租户结算人
        List<SettlementBargain> settlementBargain = settlementBargainService.list(new QueryWrapper<SettlementBargain>().lambda()
                .eq(SettlementBargain::getName, consigneeName)
                .eq(SettlementBargain::getPhone, consigneePhone)
                .eq(SettlementBargain::getLinkmanId, linkmanId)
                .eq(SettlementBargain::getTenantId, businessUtil.getTenantId()));
        if (settlementBargain.size() < 1) {
            SettlementBargain settlementBargain1 = new SettlementBargain();
            settlementBargain1.setName(consigneeName);
            settlementBargain1.setPhone(consigneePhone);
            settlementBargain1.setTenantId(businessUtil.getTenantId());
            settlementBargain1.setLinkmanId(linkmanId);

            settlementBargainService.save(settlementBargain1);
        }
        //添加个人账号
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getPhone, consigneePhone)
                .eq(SysUser::getStatus, PublicCommon.正常)
                .eq(SysUser::getTenantId, -1));
        if (sysUser == null) {
            SysUser newUser = new SysUser();
            newUser.setTenantId(-1l);
            newUser.setStatus(PublicCommon.正常);
            newUser.setPassword(MD5Ry.md5("123456"));
            newUser.setAccount(consigneePhone);
            newUser.setPhone(consigneePhone);
            newUser.setName(consigneeName);
            sysUserService.save(newUser);


        }
    }

    @Override
    public String getLastOrderNo(Long tenantId) {
        return this.baseMapper.getLastOrderNo(tenantId);
    }

    @Override
    public boolean checkOrderUpdate(OrderVO orderVO, StringBuilder errorMsg) {
        if (orderVO == null || orderVO.getOrderSubList() == null || orderVO.getOrderSubList().size() == 0) {
            errorMsg.append("参数错误");
            return false;
        }
        // 现付到付欠付月结必须要能够整除
        if (!checkFinanceData(orderVO)) {
            errorMsg.append("财务应收款必须为车辆数量的整数倍, 否则请分开录单");
            return false;
        }

        //运输费不能为空 不能为0
        if (orderVO.getTransportFee() == null || orderVO.getTransportFee().compareTo(BigDecimal.ZERO) != 1) {
            errorMsg.append("运输费必须大于0");
            return false;
        }

        // 已发运的订单不可修改
        List<Long> orderIdList = orderVO.getOrderSubList().stream().map(OrderSub::getId).collect(Collectors.toList());
        // 已取消的订单不可修改
        for (Long id : orderIdList) {
            int status = this.baseMapper.getStatusById(id);
            if (status == OrderStatusEnum.HAD_WITHDRAWN.status) {
                errorMsg.append("已取消的订单不可修改");
                return false;
            }
            if (status == OrderStatusEnum.CUSTOMER_HAS_SIGN.status) {
                errorMsg.append("已完成的订单不可修改");
                return false;
            }
        }
        int maxStatus = getMaxStatusByOrderIdList(orderIdList);
        /*if (maxStatus > 300) {
            errorMsg.setErrorMsg("已经发运的订单不可修改，请联系管理员修改！");
            return false;
        }*/
        // 是否可以统一修改
        OrderVO old = getOrderVOByOrderIdList(orderIdList);
        Set<String> updateVersionSet = old.getOrderSubList().stream().map(OrderSub::getUpdateVersion).collect(Collectors.toSet());
        if (updateVersionSet.size() > 1) {
            errorMsg.append("当前所选订单不可批量修改");
            return false;
        }
        // 提车方式、送车方式 修改
        // 原订单不需要提车
        if (old.getPickType() == PickCarTypeEnum.ZI_SONG_WAND_DIAN.type) {
            // 现在需要提车
            if (orderVO.getPickType() != PickCarTypeEnum.ZI_SONG_WAND_DIAN.type) {
                // 不需要提车改为需要提车
                // 不要改要提
                if (maxStatus > 200) {
                    errorMsg.append("当前订单状态不可修改提车方式，请联系管理员处理！");
                    return false;
                } else {
                    for (OrderSub orderSub : orderVO.getOrderSubList()) {
                        int a = this.baseMapper.getStatusById(orderSub.getId());
                        if (a == OrderStatusEnum.WAIT_PICK.status) {
                            orderSub.setStatus(OrderStatusEnum.NEW_ORDER.status);
                        }
                    }
                }
            }
        } else {
            if (orderVO.getPickType() == PickCarTypeEnum.ZI_SONG_WAND_DIAN.type) {
                // 需要提改 不提，如果已经提过车的，不可修改
                for (Long id : orderIdList) {
                    OrderPick orderPick = pickCarMapper.selectOne(new QueryWrapper<OrderPick>().lambda().eq(OrderPick::getOrderId, id));
                    if (orderPick != null) {
                        errorMsg.append("当前订单状态不可修改提车方式，请联系管理员处理！");
                        return false;
                    }
                }
                for (OrderSub orderSub : orderVO.getOrderSubList()) {
                    orderSub.setStatus(OrderStatusEnum.WAIT_PICK.status);
                }
            }
        }
        // 原来不需要送车
        if (old.getTakeType() == 3 || old.getTakeType() == 4) {
            // 不送 =》送
            if (orderVO.getTakeType() == 1 || orderVO.getTakeType() == 2) {
                for (Long id : orderIdList) {
                    int status = this.baseMapper.getStatusById(id);
                    if (status == 6 || status == 7) {
                        errorMsg.append("当前订单状态不可修改送车方式，请联系管理员处理！");
                        return false;
                    }
                }
                for (OrderSub orderSub : orderVO.getOrderSubList()) {
                    int status = this.baseMapper.getStatusById(orderSub.getId());
                    if (status == 6) {
                        orderSub.setStatus(OrderStatusEnum.FINISHED_TRANSPORT.status);
                    }
                }
            }
        } else {
            if (orderVO.getTakeType() == 3 || orderVO.getTakeType() == 4) {
                // 送 =》 不送
                for (Long id : orderIdList) {
                    OrderTake orderTake = orderTakeMapper.selectOne(new QueryWrapper<OrderTake>().lambda().eq(OrderTake::getOrderId, id));
                    if (orderTake != null) {
                        errorMsg.append("当前订单状态不可修改送车方式，请联系管理员处理！");
                        return false;
                    }
                }
                for (OrderSub orderSub : orderVO.getOrderSubList()) {
                    int status = this.baseMapper.getStatusById(orderSub.getId());
                    if (status == 5) {
                        orderSub.setStatus(OrderStatusEnum.WAIT_TAKE.status);
                    }
                }
            }
        }
        // 提送方式为非提非送，删除提送费
        /*if (orderVO.getPickType() == PickCarTypeEnum.ZI_SONG_WAND_DIAN.type) {
            orderVO.setPickFee(null);
        }
        if (orderVO.getTakeType() == TakeCarTypeEnum.ZI_SONG_WANG_DIAN.type) {
            orderVO.setTakeFee(null);
        }*/
        // 拆分每辆车的付款金额
        splitPaymentFee(orderVO);
        return true;
    }

    @Override
    public ResponseData updateOrder(OrderVO orderVO) {
        // 更新版本ID
        Long updateVersion = SnowIdUtils.uniqueLong();
        boolean needUpdateVersion = false;
        // 子订单Ids
        List<Long> orderIdList = orderVO.getOrderSubList().stream().map(OrderSub::getId).collect(Collectors.toList());
        // 子订单修改明细
        List<OrderModifyDetail> orderModifyDetails = new ArrayList<>();
        Long createUserId = LoginContextHolder.me().getSysLoginUserId();
        OrderVO old = getOrderVOByOrderIdList(orderIdList);
        for (OrderSub os : orderVO.getOrderSubList()) {
            OrderSub oldOrderSub = this.baseMapper.selectById(os.getId());
            // 车型
            if (BaseUtils.neCompareTwo(os.getCarName(), oldOrderSub.getCarName())) {
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "car_name", "车型", os.getCarName(), oldOrderSub.getCarName(), createUserId));
            }
            // 车架号
            if (BaseUtils.neCompareTwo(os.getVin(), oldOrderSub.getVin())) {
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "vin", "车架号", os.getVin(), oldOrderSub.getVin(), createUserId));
            }
            // 车价值
            if (!BaseUtils.compareDecimal(os.getCarCost(), oldOrderSub.getCarCost())) {
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "car_cost", "车价值", BaseUtils.objectToString(os.getCarCost()), BaseUtils.objectToString(oldOrderSub.getCarCost()), createUserId));
            }
            // 保险费
            if (BaseUtils.neCompareTwo(os.getHasInsurance(), oldOrderSub.getHasInsurance())) {
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "has_insurance", "有无保险费", BaseUtils.objectToString(os.getInsuranceFee()), BaseUtils.objectToString(oldOrderSub.getInsuranceFee()), createUserId));
            }
            // 保险费
            if (!BaseUtils.compareDecimal(os.getInsuranceFee(), oldOrderSub.getInsuranceFee())) {
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "insurance_fee", "保险费", BaseUtils.objectToString(os.getInsuranceFee()), BaseUtils.objectToString(oldOrderSub.getInsuranceFee()), createUserId));
            }
            // 共有的字段
            if (BaseUtils.neCompareTwo(orderVO.getCompanyName(), old.getCompanyName())) {
                needUpdateVersion = true;
                os.setCompanyName(orderVO.getCompanyName());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "company_name", "公司名称", orderVO.getCompanyName(), old.getCompanyName(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getLinkmanName(), old.getLinkmanName())) {
                needUpdateVersion = true;
                os.setLinkmanName(orderVO.getLinkmanName());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "linkman_name", "联系人", orderVO.getLinkmanName(), old.getLinkmanName(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getLinkmanPhone(), old.getLinkmanPhone())) {
                needUpdateVersion = true;
                os.setLinkmanPhone(orderVO.getLinkmanPhone());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "linkman_phone", "联系人电话", orderVO.getLinkmanPhone(), old.getLinkmanPhone(), createUserId));
            }
            os.setLinkmanId(orderVO.getLinkmanId());
            if (BaseUtils.neCompareTwo(orderVO.getConsigneeName(), old.getConsigneeName())) {
                needUpdateVersion = true;
                os.setConsigneeName(orderVO.getConsigneeName());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "consignee_name", "收货人", orderVO.getConsigneeName(), old.getConsigneeName(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getConsigneePhone(), old.getConsigneePhone())) {
                needUpdateVersion = true;
                os.setConsigneePhone(orderVO.getConsigneePhone());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null, "consignee_phone", "收货人电话", orderVO.getConsigneePhone(), old.getConsigneePhone(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getStartCode(), old.getStartCode())) {
                needUpdateVersion = true;
                os.setStartCode(orderVO.getStartCode());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "start_code", "出发地", cmCityMapper.getNameByCode(orderVO.getStartCode()), cmCityMapper.getNameByCode(old.getStartCode()), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getDestinationCode(), old.getDestinationCode())) {
                needUpdateVersion = true;
                os.setDestinationCode(orderVO.getDestinationCode());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "destination_code", "目的地", cmCityMapper.getNameByCode(orderVO.getDestinationCode()), cmCityMapper.getNameByCode(old.getDestinationCode()), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getPickType(), old.getPickType())) {
                needUpdateVersion = true;
                os.setPickType(orderVO.getPickType());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "pick_type", "提车方式", PickCarTypeEnum.getValue(orderVO.getPickType()), PickCarTypeEnum.getValue(old.getPickType()), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getTakeType(), old.getTakeType())) {
                needUpdateVersion = true;
                os.setTakeType(orderVO.getTakeType());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "take_type", "送车方式", TakeCarTypeEnum.getValue(orderVO.getTakeType()), TakeCarTypeEnum.getValue(old.getTakeType()), createUserId));
            }
            if (!BaseUtils.compareDecimal(os.getPickFee(), oldOrderSub.getPickFee())) {
                needUpdateVersion = true;
                //os.setPickFee(orderVO.getPickFee());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "pick_fee", "提车费", BaseUtils.objectToString(os.getPickFee()), BaseUtils.objectToString(oldOrderSub.getPickFee()), createUserId));
            }
            if (!BaseUtils.compareDecimal(os.getTakeFee(), oldOrderSub.getTakeFee())) {
                needUpdateVersion = true;
                //os.setTakeFee(orderVO.getTakeFee());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "take_fee", "送车费", BaseUtils.objectToString(os.getTakeFee()), BaseUtils.objectToString(oldOrderSub.getTakeFee()), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getPickLinkmanName(), old.getPickLinkmanName())) {
                needUpdateVersion = true;
                os.setPickLinkmanName(orderVO.getPickLinkmanName());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "pick_linkman_name", "提车联系人", orderVO.getPickLinkmanName(), old.getPickLinkmanName(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getPickLinkmanPhone(), old.getPickLinkmanPhone())) {
                needUpdateVersion = true;
                os.setPickLinkmanPhone(orderVO.getPickLinkmanPhone());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "pick_linkman_phone", "提车联系人电话", orderVO.getPickLinkmanPhone(), old.getPickLinkmanPhone(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getPickAreaCode(), old.getPickAreaCode())) {
                needUpdateVersion = true;
                os.setPickAreaCode(orderVO.getPickAreaCode());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "pick_area_code",
                        "提车区域",
                        StringUtils.isBlank(orderVO.getPickAreaCode()) ? "" : cmAreaMapper.getNameByCode(orderVO.getPickAreaCode()),
                        StringUtils.isBlank(old.getPickAreaCode()) ? "" : cmAreaMapper.getNameByCode(old.getPickAreaCode()),
                        createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getPickAddress(), old.getPickAddress())) {
                needUpdateVersion = true;
                os.setPickAddress(orderVO.getPickAddress());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "pick_address", "提车地址", orderVO.getPickAddress(), old.getPickAddress(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getTakeLinkmanName(), old.getTakeLinkmanName())) {
                needUpdateVersion = true;
                os.setTakeLinkmanName(orderVO.getTakeLinkmanName());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "take_linkman_name", "送车联系人", orderVO.getTakeLinkmanName(), old.getTakeLinkmanName(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getTakeLinkmanPhone(), old.getTakeLinkmanPhone())) {
                needUpdateVersion = true;
                os.setTakeLinkmanPhone(orderVO.getTakeLinkmanPhone());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "take_linkman_phone", "送车联系人电话", orderVO.getTakeLinkmanPhone(), old.getTakeLinkmanPhone(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getTakeAreaCode(), old.getTakeAreaCode())) {
                needUpdateVersion = true;
                os.setTakeAreaCode(orderVO.getTakeAreaCode());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "take_area_code",
                        "送车区域",
                        StringUtils.isBlank(orderVO.getTakeAreaCode()) ? "" : cmAreaMapper.getNameByCode(orderVO.getTakeAreaCode()),
                        StringUtils.isBlank(old.getTakeAreaCode()) ? "" : cmAreaMapper.getNameByCode(old.getTakeAreaCode()),
                        createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getTakeAddress(), old.getTakeAddress())) {
                needUpdateVersion = true;
                os.setTakeAddress(orderVO.getTakeAddress());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "take_address", "送车地址", orderVO.getTakeAddress(), old.getTakeAddress(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getHasUrgent(), old.getHasUrgent())) {
                needUpdateVersion = true;
                os.setHasUrgent(orderVO.getHasUrgent());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "has_urgent", "是否加急", YesOrNoEnum.getValue(orderVO.getHasUrgent()), YesOrNoEnum.getValue(old.getHasUrgent()), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getAppointPickTime(), old.getAppointPickTime())) {
                needUpdateVersion = true;
                if (orderVO.getAppointPickTime() != null) {
                    os.setAppointPickTime(orderVO.getAppointPickTime());
                }
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "appoint_pick_time", "预约提车时间", BaseUtils.objectToString(orderVO.getAppointPickTime()), BaseUtils.objectToString(old.getAppointPickTime()), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getRemark(), old.getRemark())) {
                needUpdateVersion = true;
                os.setRemark(orderVO.getRemark());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "remark", "备注", orderVO.getRemark(), old.getRemark(), createUserId));
            }
            if (BaseUtils.neCompareTwo(orderVO.getTransportType(), old.getTransportType())) {
                needUpdateVersion = true;
                os.setTransportType(orderVO.getTransportType());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "transport_type", "运输方式", TransportWayEnum.getValue(orderVO.getTransportType()), TransportWayEnum.getValue(old.getTransportType()), createUserId));
            }
            // 财务相关
            if (!BaseUtils.compareDecimal(orderVO.getTransportFee(), old.getTransportFee())) {
                needUpdateVersion = true;
                os.setTransportFee(orderVO.getTransportFee());
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "transport_fee", "运输费", BaseUtils.objectToString(orderVO.getTransportFee()), BaseUtils.objectToString(old.getTransportFee()), createUserId));
            }

            if (!Arrays.equals(orderVO.getPaymentType(), old.getPaymentType())) {
                needUpdateVersion = true;
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "payment_type", "付款方式", BaseUtils.paymentArrayToStr(orderVO.getPaymentType()), BaseUtils.paymentArrayToStr(old.getPaymentType()), createUserId));
            }
            // 税额
            if (!BaseUtils.compareDecimal(os.getInvoiceFee(), oldOrderSub.getInvoiceFee())) {
                needUpdateVersion = true;
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "invoice_fee", "税额", BaseUtils.objectToString(os.getInvoiceFee()), BaseUtils.objectToString(oldOrderSub.getInvoiceFee()), createUserId));
            }
            // 财务相关连的改动
            // 1. 如果改了客户联系人，需要修改现付，欠付，月结，返款的结算人
            if (BaseUtils.neCompareTwo(orderVO.getLinkmanId(), old.getLinkmanId())) {
                financeMapper.updateCollectionSettlementInfo(os.getId(), orderVO.getLinkmanName(), orderVO.getLinkmanPhone());
                financeDetailMapper.updateSettlementUserInfo(os.getId(), 1, orderVO.getLinkmanName(), orderVO.getLinkmanPhone(), orderVO.getLinkmanId());
                financeDetailMapper.updateSettlementUserInfo(os.getId(), 3, orderVO.getLinkmanName(), orderVO.getLinkmanPhone(), orderVO.getLinkmanId());
                financeDetailMapper.updateSettlementUserInfo(os.getId(), 4, orderVO.getLinkmanName(), orderVO.getLinkmanPhone(), orderVO.getLinkmanId());
                financeDetailMapper.updateSettlementUserInfo(os.getId(), 5, orderVO.getLinkmanName(), orderVO.getLinkmanPhone(), orderVO.getLinkmanId());
            }
            // 返款
            if (!BaseUtils.compareDecimal(os.getKickbackFee(), oldOrderSub.getKickbackFee())) {
                needUpdateVersion = true;
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "kickback_fee", "返款", BaseUtils.objectToString(os.getKickbackFee()), BaseUtils.objectToString(oldOrderSub.getKickbackFee()), createUserId));
                try {
                    modifyOrderFeeDetail(os.getId(),
                            FinanceTypeEnum.KICKBACK.type,
                            os.getKickbackFee(),
                            oldOrderSub.getKickbackFee(),
                            orderVO.getLinkmanId().toString(),
                            orderVO.getLinkmanName(),
                            orderVO.getLinkmanPhone());
                } catch (Exception e) {
                    throw new CustomException(e.getMessage());
                }

            }

            //如果现付金额不一致且现付已经通过线上完成支付，此时就不能修改现付金额
            if (os.getSpotPayFee() != null && oldOrderSub.getSpotPayFee() != null) {
                if (os.getSpotPayFee().compareTo(oldOrderSub.getSpotPayFee()) != 0) {
                    //根据订单id查询
                    Integer integer = payOrderConfigMapper.selectCount(new LambdaQueryWrapper<PayOrderConfig>()
                            .eq(PayOrderConfig::getOrderId, os.getId()));

                    if (integer > 0) {
                        return ResponseData.error("已经完成现付金额的线上支付，不能再修改现付金额");
                    }
                }
            }

            // 现付
            if (!BaseUtils.compareDecimal(os.getSpotPayFee(), oldOrderSub.getSpotPayFee())) {
                needUpdateVersion = true;
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "spot_pay_fee", "现付", BaseUtils.objectToString(os.getSpotPayFee()), BaseUtils.objectToString(oldOrderSub.getSpotPayFee()), createUserId));
                try {
                    this.modifyOrderFeeDetail(os.getId(),
                            FinanceTypeEnum.SPOT.type,
                            os.getSpotPayFee(),
                            oldOrderSub.getSpotPayFee(),
                            orderVO.getLinkmanId().toString(),
                            orderVO.getLinkmanName(),
                            orderVO.getLinkmanPhone());
                } catch (Exception e) {
                    throw new CustomException(e.getMessage());
                }
            }
            // 到付
            if (!BaseUtils.compareDecimal(os.getDeliveryPayFee(), oldOrderSub.getDeliveryPayFee())) {
                needUpdateVersion = true;
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "delivery_pay_fee", "到付", BaseUtils.objectToString(os.getDeliveryPayFee()), BaseUtils.objectToString(oldOrderSub.getDeliveryPayFee()), createUserId));
                try {
                    modifyOrderFeeDetail(os.getId(),
                            FinanceTypeEnum.DELIVERY.type,
                            os.getDeliveryPayFee(),
                            oldOrderSub.getDeliveryPayFee(),
                            orderVO.getLinkmanId().toString(),
                            orderVO.getLinkmanName(),
                            orderVO.getLinkmanPhone());
                } catch (Exception e) {
                    throw new CustomException(e.getMessage());
                }
            }
            // 欠付
            if (!BaseUtils.compareDecimal(os.getBackPayFee(), oldOrderSub.getBackPayFee())) {
                needUpdateVersion = true;
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "back_pay_fee", "欠付", BaseUtils.objectToString(os.getBackPayFee()), BaseUtils.objectToString(oldOrderSub.getBackPayFee()), createUserId));
                try {
                    modifyOrderFeeDetail(os.getId(),
                            FinanceTypeEnum.BACK_PAY.type,
                            os.getBackPayFee(),
                            oldOrderSub.getBackPayFee(),
                            orderVO.getLinkmanId().toString(),
                            orderVO.getLinkmanName(),
                            orderVO.getLinkmanPhone());
                } catch (Exception e) {
                    throw new CustomException(e.getMessage());
                }
            }
            // 月结
            if (!BaseUtils.compareDecimal(os.getSlotPayFee(), oldOrderSub.getSlotPayFee())) {
                needUpdateVersion = true;
                orderModifyDetails.add(new OrderModifyDetail(os.getId(), null,
                        "slot_pay_fee", "月结", BaseUtils.objectToString(os.getSlotPayFee()), BaseUtils.objectToString(oldOrderSub.getSlotPayFee()), createUserId));
                try {
                    modifyOrderFeeDetail(os.getId(),
                            FinanceTypeEnum.SLOT.type,
                            os.getSlotPayFee(),
                            oldOrderSub.getSlotPayFee(),
                            orderVO.getLinkmanId().toString(),
                            orderVO.getLinkmanName(),
                            orderVO.getLinkmanPhone());
                } catch (Exception e) {
                    throw new CustomException(e.getMessage());
                }
            }
            // 总运费
            /*BigDecimal totalFee = orderVO.getTransportFee() == null ? BigDecimal.ZERO : orderVO.getTransportFee()
                    .add(os.getInsuranceFee() == null ? BigDecimal.ZERO : os.getInsuranceFee())
                    .add(os.getKickbackFee() == null ? BigDecimal.ZERO : os.getKickbackFee())
                    .add(os.getInvoiceFee() == null ? BigDecimal.ZERO : os.getInvoiceFee())
                    .add(os.getPickFee() == null ? BigDecimal.ZERO : os.getPickFee())
                    .add(os.getTakeFee() == null ? BigDecimal.ZERO : os.getTakeFee());*/
            os.setTotalFee(getOrderSubTotalFee(os));
            // 更新版本号
            if (needUpdateVersion) {
                os.setUpdateVersion(updateVersion.toString());
            }
            os.setPaymentType(Arrays.toString(orderVO.getPaymentType()));
            this.updateById(os);
            // finance表状态更新
            financeService.changeFinanceStatus(os.getId());
        }
        // 订单修改明细
        if (orderModifyDetails.size() > 0) {
            for (OrderModifyDetail omd : orderModifyDetails) {
                orderModifyDetailMapper.insert(omd);
            }
        }

        return ResponseData.success();
    }

    @Autowired
    private SysEmpMapper sysEmpMapper;


    @Override
    public ResponseData getOrderListPage(OrderDTO orderDTO) {
        orderDTO.setTenantId(businessUtil.getTenantId());
        //用户登录
        if (businessUtil.getTenantId() == -1) {
            SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
            orderDTO.setConsigneePhone(sysLoginUser.getAccount());
        }
        //如果是网点人员，查询该网点人员所在网点的服务城市，以及自己创建订单的出发地
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        List<String> roleCodeList = sysUserService.getRoleCodeListByUserId(sysLoginUserId);
        if (roleCodeList.contains(RoleConstant.网点部角色)) {
            //查询该网点人员所在网点的服务城市，以及自己创建订单的出发地 的城市code
            setSiteCityCodeList(orderDTO, sysLoginUserId);
        }
        //获取用户权限数据
        Page<PkgOrderSub> list = this.baseMapper.getOrderListPage(PageFactory.defaultPage(), orderDTO);
        //判断每个订单是否现付已经线上支付过
        if (list != null && !list.getRecords().isEmpty()) {
            List<PkgOrderSub> records = list.getRecords();
            List<String> subIdList = records.stream().map(x -> x.getId()).collect(Collectors.toList());
            List<PayOrderConfig> payOrderConfigs = payOrderConfigMapper.selectList(new QueryWrapper<PayOrderConfig>().lambda().in(PayOrderConfig::getOrderId, subIdList));
            List<Long> payOrderIdList = payOrderConfigs.stream().map(x -> x.getOrderId()).collect(Collectors.toList());
            if (records != null && records.size() > 0) {
                List<PkgOrderSub> records1 = new ArrayList<>();
                for (PkgOrderSub record : records) {
                    if (payOrderIdList.contains(record.getId())) {
                        record.setIsPay("1");
                    } else {
                        record.setIsPay("2");
                    }
                    records1.add(record);
                }
                list.setRecords(records1);
            }
        }
        //判断订单状态
        Integer orderStatus = orderDTO.getOrderStatus();
        //如果为1即待签收
        if (Objects.nonNull(orderStatus) && orderStatus == 1) {
            //只要订单状态为4的订单
            if (Objects.nonNull(list)) {
                List<PkgOrderSub> pkgOrderSubList = list.getRecords();
                if (CollectionUtil.isNotEmpty(pkgOrderSubList)) {
                    pkgOrderSubList = pkgOrderSubList.stream().filter(s -> s.getStatus() == 4)
                            .collect(Collectors.toList());
                    list.setRecords(pkgOrderSubList);
                }
            }
        }
        //如果为2即待付
        if (Objects.nonNull(orderStatus) && orderStatus == 2) {
            //只要待交付状态订单
            if (Objects.nonNull(list)) {
                List<PkgOrderSub> pkgOrderSubList = list.getRecords();
                if (CollectionUtil.isNotEmpty(pkgOrderSubList)) {
                    pkgOrderSubList = pkgOrderSubList.stream().filter(s -> s.getStatus() == 6)
                            .collect(Collectors.toList());
                    list.setRecords(pkgOrderSubList);
                }
            }
        }

        // 合计行
        AndaPageResult andaPageResult = new AndaPageResult();
        andaPageResult.setSummary(this.baseMapper.getOrderListSummary(orderDTO));
        andaPageResult.AndaPageResult(list, orderDTO);
        return ResponseData.andaSuccess(andaPageResult);
    }

    @Override
    public void setSiteCityCodeList(OrderDTO orderDTO, Long sysLoginUserId) {
        //创建集合用来保存城市code
        List<String> cityCodeList = new ArrayList<>();

        //查询该网点人员所在网点的服务城市code
        List<String> siteCityCodeList = sysEmpMapper.selectCityCodeByUserId(sysLoginUserId);

        if (CollectionUtil.isNotEmpty(siteCityCodeList)) {
            cityCodeList.addAll(siteCityCodeList);
        }

        if (CollectionUtil.isNotEmpty(cityCodeList)) {
            orderDTO.setStartCodes(cityCodeList);
            orderDTO.setDispatcherId(sysLoginUserId.toString());
        }

        cityCodeList.add("-1");
    }

    @Override
    public PkgOrderSub getOrderDetail(Long id, Integer scene, Long transportId) {
        PkgOrderSub orderSub = this.baseMapper.getOrderDetail(id);
        if (orderSub == null) {
            throw new CustomException("数据不存在");
        }

        //判断现付是否已经线上支付过
        Integer integer = payOrderConfigMapper.selectCount(new LambdaQueryWrapper<PayOrderConfig>()
                .eq(PayOrderConfig::getOrderId, id));
        if (integer > 0) {
            orderSub.setIsPay("1");
        } else {
            orderSub.setIsPay("2");
        }

        // 提车地址、送车地址拼接省市区
        orderSub.setPickAddress(concatAddress(orderSub.getPickAddress(), orderSub.getStartCode(), orderSub.getPickAreaCode()));
        orderSub.setTakeAddress(concatAddress(orderSub.getTakeAddress(), orderSub.getDestinationCode(), orderSub.getTakeAreaCode()));
        // 订单应付费用明细
        List<ExtraFeeVO> paymentDetailList = orderPaymentList(id, scene);
        BigDecimal totalPaymentFee = BigDecimal.ZERO;
        if (paymentDetailList.size() > 0) {
            totalPaymentFee = paymentDetailList.stream().map(ExtraFeeVO::getFee).reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        orderSub.setTotalPaymentFee(totalPaymentFee);
        orderSub.setPaymentDetailList(paymentDetailList);
        // 额外费用
        List<OrderExtraFee> orderExtraFeeList = orderExtraFeeMapper.selectList(new QueryWrapper<OrderExtraFee>().lambda().eq(OrderExtraFee::getOrderId, id));
        if (scene != null && scene.equals(3)) {
            orderExtraFeeList = orderExtraFeeList.stream().filter(e -> e.getAddScene().equals(3)).collect(Collectors.toList());
        }
        orderSub.setExtraFeeList(orderExtraFeeList);
        // 提车信息
        PkgPick orderPick = pickCarMapper.getPkgPickDetail(id);
        orderSub.setOrderPick(orderPick);
        // 验车信息
        orderSub.setOrderCarVerify(orderCarVerifyMapper.getPkgOrderCarVerify(id));
        // 入库信息
        orderSub.setOrderStock(orderStockMapper.getPkgOrderStock(id));
        // app在途信息
        List<OrderLogistics> appLogistics = new ArrayList<>();
        // 承运信息
        List<PkgTransportLevelDetailSimple> transportList = transportLevelDetailMapper.getPkgTransportLevelDetailSimpleListByOrderId(id);
        if (transportList != null && transportList.size() > 0) {
            for (PkgTransportLevelDetailSimple tld : transportList) {
                // 运单签收信息
                tld.setOrderSign(orderSignMapper.getPkgOrderSignByOrderIdAndTransportId(tld.getTransportSimple().getId(), id));
                // 运单在途跟踪信息
                List<OrderLogistics> orderLogisticsList = logisticsMapper.getLogisticsListByTransportId(tld.getTransportSimple().getId());
                tld.setLogisticsList(orderLogisticsList);
                appLogistics.addAll(orderLogisticsList);
            }
        }
        orderSub.setTransportSimpleList(transportList);
        // app端在途信息
        if (appLogistics.size() > 0) {
            orderSub.setAppLogistics(appLogistics.stream().sorted(Comparator.comparing(OrderLogistics::getCreateTime)).collect(Collectors.toList()));
        }
        // 签收信息 scene = 3, 签收记录详情显示
        if (scene == 3 && transportId != null) {
            orderSub.setOrderSign(orderSignMapper.getPkgOrderSignByOrderIdAndTransportId(transportId, id));
        }
        // 送车信息
        PkgTake take = orderTakeMapper.getPkgTakeDetail(id);
        orderSub.setOrderTake(take);
        // 交付信息
        PkgOrderFinishRecord pkgOrderFinishRecord = orderFinishRecordMapper.getPkgOrderFinishRecordDetailByOrderId(id);
        // 线上支付信息
        if (pkgOrderFinishRecord != null) {
            if (pkgOrderFinishRecord.getType() != null &&
                    pkgOrderFinishRecord.getType() == 1 && StringUtils.isNotBlank(pkgOrderFinishRecord.getClientSn())) {
                PkgOnlinePayRecord onlinePayRecord = orderPayRecordMapper.getSuccessRecordByClientSn(pkgOrderFinishRecord.getClientSn());
                pkgOrderFinishRecord.setOnlinePayRecord(onlinePayRecord);
            }
            // 交付图片
            List<String> takeCarImageList = orderFinishImageMapper.getImageByIdAndType(pkgOrderFinishRecord.getId(), 1);
            pkgOrderFinishRecord.setTakeCarImageList(takeCarImageList);
            List<String> paymentImageList = orderFinishImageMapper.getImageByIdAndType(pkgOrderFinishRecord.getId(), 2);
            pkgOrderFinishRecord.setPaymentImageList(paymentImageList);
        }
        orderSub.setOrderFinish(pkgOrderFinishRecord);
        // 订单修改记录
        orderSub.setModifyList(orderModifyDetailMapper.getByOrderId(id));
        // app评价信息
     /*   OrderEvaluation oe = orderEvaluationMapper.selectOne(new QueryWrapper<OrderEvaluation>().lambda()
                .eq(OrderEvaluation::getOrderId, id));
        orderSub.setOrderEvaluation(oe);*/
        // app在途信息
        //orderSub.setAppLogistics(getAppLogisticsByOrderId(id));
        PkgOrderCarVerify verify = orderCarVerifyService.getVerifyInfo(id);
        orderSub.setPkgOrderCarVerify(verify);
        return orderSub;
    }

    @Autowired
    private OrderCarVerifyService orderCarVerifyService;


    /**
     * 获取订单应付费用
     *
     * @param orderId
     * @param scene   场景 1.订单详情 2.提车详情 3，签收详情 4.送车详情
     * @return
     */
    private List<ExtraFeeVO> orderPaymentList(Long orderId, Integer scene) {
        List<ExtraFeeVO> list = new ArrayList<>();
        List<FinanceDetail> paymentDetailList = financeDetailMapper.selectList(new QueryWrapper<FinanceDetail>().lambda()
                .eq(FinanceDetail::getOrderId, orderId).and(wrapper -> wrapper.ge(FinanceDetail::getType, 5)));
        if (paymentDetailList != null && paymentDetailList.size() > 0) {
            Iterator<FinanceDetail> iterator = paymentDetailList.iterator();
            while (iterator.hasNext()) {
                int type = iterator.next().getType();
                if (scene == 2) {
                    if (type != 6 && type != 9) {
                        iterator.remove();
                    }
                } else if (scene == 3) {
                    if (type != 8 && type != 9) {
                        iterator.remove();
                    }
                } else if (scene == 4) {
                    if (type != 7 && type != 9) {
                        iterator.remove();
                    }
                }
            }
            for (FinanceDetail fd : paymentDetailList) {
                if (fd.getType() == 9) {
                    //OrderExtraFee orderExtraFee = orderExtraFeeMapper.selectById(fd.getRelationId());
                    PkgOrderExtraFee oef = orderExtraFeeMapper.getPkgOrderExtraFeeById(fd.getRelationId());
                    if (oef != null) {
                        list.add(new ExtraFeeVO(ExtraFeeType.getValue(oef.getType()), fd.getNeedSettlement(), fd.getSettlementUser(), fd.getSettlementPhone(),
                                oef.getCreateUserName(), oef.getCreateTime(), ExtraFeeScene.getValue(oef.getAddScene())));
                    }
                } else {
                    if (fd.getType() == 6) {
                        PkgPick pick = pickCarMapper.getPkgPickDetail(fd.getOrderId());
                        if (pick != null) {
                            list.add(new ExtraFeeVO("提车费", fd.getNeedSettlement(), fd.getSettlementUser(), fd.getSettlementPhone(),
                                    pick.getCreateUserName(), pick.getCreateTime(), null));
                        }

                    }
                    if (fd.getType() == 7) {
                        PkgTake take = orderTakeMapper.getPkgTakeDetail(fd.getOrderId());
                        if (take != null) {
                            list.add(new ExtraFeeVO("送车费", fd.getNeedSettlement(), fd.getSettlementUser(), fd.getSettlementPhone(),
                                    take.getCreateUserName(), take.getCreateTime(), null));
                        }

                    }
                    if (fd.getType() == 8) {
                        PkgTransportSimple transport = transportMapper.getPkgTransportSimpleById(fd.getRelationId());
                        if (transport != null) {
                            list.add(new ExtraFeeVO("承运费(" + transport.getTransportNo() + ")", fd.getNeedSettlement(), fd.getSettlementUser(), fd.getSettlementPhone(),
                                    transport.getCreateUserName(), transport.getCreateTime(), null));
                        }

                    }
                    //list.add(new ExtraFeeVO(FinanceTypeEnum.getValue(fd.getType()), fd.getNeedSettlement()));
                }
            }
        }
        return list;
    }


    /**
     * 根据城市code和区code拼接详细地址
     *
     * @param originAddress 具体地址
     * @param cityCode      城市code
     * @param areaCode      区code
     * @return realAddress
     */
    private String concatAddress(String originAddress, String cityCode, String areaCode) {
        // 如果原来地址没有填，则直接返回
        if (StringUtils.isBlank(originAddress)) {
            return originAddress;
        }
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(cityCode)) {
            CmCity city = cmCityMapper.getCityByCode(cityCode);
            if (city != null) {
                if (city.getHasCounty() == 1) {
                    // 县级市
                    sb.append(city.getProvinceName()).append(city.getCityName()).append(city.getName());
                } else {
                    // 地级市
                    // 直辖市不拼接省--京津沪渝
                    if (city.getName().contains("北京") || city.getName().contains("上海")
                            || city.getName().contains("天津") || city.getName().contains("重庆")) {
                        sb.append(city.getName());
                    } else {
                        sb.append(city.getProvinceName()).append(city.getName());
                    }
                }
                if (StringUtils.isNotBlank(areaCode)) {
                    CmArea area = cmAreaMapper.getAreaByCode(areaCode);
                    if (area != null) {
                        sb.append(area.getName());
                    }
                }
            }
        }
        return sb.append(originAddress).toString();
    }


    /**
     * 订单修改财务相关字段处理
     *
     * @param orderId      orderId
     * @param financeType  类型
     * @param fee          金额
     * @param oldFee       原金额
     * @param linkmanId    结算人ID
     * @param linkmanName  结算人
     * @param linkmanPhone 结算人电话
     */
    @Transactional
    public void modifyOrderFeeDetail(Long orderId, int financeType, BigDecimal fee, BigDecimal oldFee, String linkmanId, String linkmanName, String linkmanPhone) throws Exception {


        FinanceDetail fd = financeDetailMapper.selectOne(new QueryWrapper<FinanceDetail>().lambda()
                .eq(FinanceDetail::getOrderId, orderId)
                .and(wrapper -> wrapper.eq(FinanceDetail::getType, financeType)));
        if (oldFee == null || oldFee.compareTo(BigDecimal.ZERO) == 0) {
            // 无 --> 有
            if (financeType != 2) {
                updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee, BigDecimal.ZERO, linkmanName, linkmanPhone);
                FinanceDetail fd1 = new FinanceDetail();
                fd1.setId(SnowIdUtils.uniqueLong());
                fd1.setOrderId(orderId);
                fd1.setSettlementUserId(Long.valueOf(linkmanId));
                fd1.setSettlementUser(linkmanName);
                fd1.setSettlementPhone(linkmanPhone);
                fd1.setType(financeType);
                fd1.setNeedSettlement(fee);
                fd1.setHasSettlement(BigDecimal.ZERO);
                fd1.setUnSettlement(fee);
                financeDetailMapper.insert(fd1);
            } else {
                // 到付
                Map<String, String> map = getDeliveryPaySettlementUser(orderId);
                if (map.get("name") != null) {
                    updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee, BigDecimal.ZERO, map.get("name"), map.get("phone"));
                    FinanceDetail fd1 = new FinanceDetail();

                    fd1.setOrderId(orderId);
                    fd1.setSettlementUserId(Long.valueOf(map.get("settlementId") == null ? "0" : map.get("settlementId")));
                    fd1.setSettlementUser(map.get("name"));
                    fd1.setSettlementPhone(map.get("phone"));
                    fd1.setType(financeType);
                    fd1.setNeedSettlement(fee);
                    fd1.setHasSettlement(BigDecimal.ZERO);
                    fd1.setUnSettlement(fee);
                    financeDetailMapper.insert(fd1);
                } else {
                    updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee, BigDecimal.ZERO, "", "");
                }
            }

        } else if (fee == null || fee.compareTo(BigDecimal.ZERO) == 0) {
            // 有 --> 无
            try {
                if (fd != null) {
                    if (fd.getStatus() == 2) {
                        // 已经结算不可修改，不可删除
                        throw new CustomException("已经结算不可修改");
                    } else if (fd.getStatus() == 1) {
                        // 部分结算
                        throw new CustomException("已经结算不可修改");
                    } else {
                        // 未结算的，删除对应费用信息
                        updateOrderFinanceInfo(orderId.toString(), financeType, null, null, null, "", "");
                        financeDetailMapper.deleteById(fd.getId());
                    }
                } else {
                    updateOrderFinanceInfo(orderId.toString(), financeType, null, null, null, "", "");
                }
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        } else {
            // 修改金额
            try {
                if (fd != null) {
                    if (fd.getHasSettlement().compareTo(BigDecimal.ZERO) > 0 && fee.compareTo(fd.getHasSettlement()) < 0) {
                        // 不可改为小于已经结算的金额
                        throw new CustomException("不可改为小于已经结算的金额");
                    } else {
                        if (financeType == 2) {
                            financeMapper.updateDeliveryFeeOnly(orderId.toString(), fee.subtract(fd.getHasSettlement()), fd.getHasSettlement());
                        } else {
                            updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee.subtract(fd.getHasSettlement()), fd.getHasSettlement(), linkmanName, linkmanPhone);
                        }
                        fd.setNeedSettlement(fee);
                        //fd.setHasSettlement(BigDecimal.ZERO);
                        fd.setUnSettlement(fee.subtract(fd.getHasSettlement()));
                        if (fd.getUnSettlement().compareTo(BigDecimal.ZERO) == 0) {
                            fd.setStatus(2);
                        } else {
                            fd.setStatus(0);
                        }
                        financeDetailMapper.updateById(fd);
                    }
                } else {
                    // 到付金额未发运，未签收之前可能是null，只更新finance表即可
                    Map<String, String> map = getDeliveryPaySettlementUser(orderId);
                    updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee, BigDecimal.ZERO, map.get("name"), map.get("phone"));
                }

            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        }
    }


    /**
     * 获取订单到付结算人
     *
     * @param orderId
     * @return
     */
    private Map<String, String> getDeliveryPaySettlementUser(Long orderId) {
        Map<String, String> map = new HashMap<>();
        TransportLevelDetail lastTld = transportLevelDetailMapper.getLastTransportLevelDetail(orderId);
        if (lastTld == null) {
            map.put("name", "");
            map.put("phone", "");
        } else {
            TransportLevel lastTl = transportLevelMapper.selectById(lastTld.getLevelId());
            Transport t = transportMapper.selectOne(new QueryWrapper<Transport>().lambda().eq(Transport::getId, lastTl.getTransportId()));
            if (lastTl.getType() == 2) {
                // 直交客户，结算人为承运公司
                map.put("name", t.getSettlementUser());
                map.put("phone", t.getSettlementPhone());
                map.put("settlementId", t.getSettlementId().toString());
            } else {
                // 有无到达签收
                PkgOrderSign ts = orderSignMapper.getDeliverySignByOrderId(orderId);
                if (ts != null) {
                    SysSite site = siteMapper.selectById(lastTl.getSiteId());
                    map.put("name", site.getName());
                    map.put("phone", "111");
                    map.put("settlementId", site.getId().toString());
                } else {
                    map.put("name", "");
                    map.put("phone", "");
                }
            }
        }
        return map;
    }


    private void updateOrderFinanceInfo(String orderId, int financeType, BigDecimal needSettlementFee, BigDecimal unSettlementFee, BigDecimal hasSettlementFee, String linkmanName, String linkmanPhone) {
        FinanceTypeEnum typeEnum = FinanceTypeEnum.getByType(financeType);
        assert typeEnum != null;
        switch (typeEnum) {
            case KICKBACK:
                financeMapper.updateKickBackFeeByOrderId(orderId, unSettlementFee, hasSettlementFee, linkmanName, linkmanPhone);
                break;
            case SPOT:
                financeMapper.updateSpotPayFeeByOrderId(orderId, unSettlementFee, hasSettlementFee, linkmanName, linkmanPhone);
                break;
            case DELIVERY:
                financeMapper.updateDeliveryFeeByOrderId(orderId, unSettlementFee, hasSettlementFee, linkmanName, linkmanPhone);
                break;
            case BACK_PAY:
                financeMapper.updateBackPayFeeByOrderId(orderId, unSettlementFee, hasSettlementFee, linkmanName, linkmanPhone);
                break;
            case SLOT:
                financeMapper.updateSlotPayFeeByOrderId(orderId, unSettlementFee, hasSettlementFee, linkmanName, linkmanPhone);
                break;
            case PICK:
                financeMapper.updatePickFeeByOrderId(orderId, needSettlementFee, unSettlementFee, hasSettlementFee, linkmanName, linkmanPhone);
                break;
            case TAKE:
                financeMapper.updateTakeFeeByOrderId(orderId, needSettlementFee, unSettlementFee, hasSettlementFee, linkmanName, linkmanPhone);
                break;
            default:
        }
    }


    @Override
    public OrderVO getOrderVOByOrderIdList(List<Long> idList) {
        List<OrderSub> orderSubList = this.baseMapper.selectList(new QueryWrapper<OrderSub>().lambda()
                .in(OrderSub::getId, idList));
        OrderSub os = orderSubList.get(0);
        OrderVO orderVO = new OrderVO();
        orderVO.setId(os.getOrderId());
        orderVO.setCompanyName(os.getCompanyName());
        orderVO.setLinkmanId(os.getLinkmanId());
        orderVO.setCanSlotPay(linkmanMapper.getNatureById(os.getLinkmanId()));
        orderVO.setLinkmanName(os.getLinkmanName());
        orderVO.setLinkmanPhone(os.getLinkmanPhone());
        orderVO.setConsigneeName(os.getConsigneeName());
        orderVO.setConsigneePhone(os.getConsigneePhone());
        orderVO.setStartCode(os.getStartCode());
        orderVO.setDestinationCode(os.getDestinationCode());
        orderVO.setStartCodeName(cmCityMapper.getNameByCode(os.getStartCode()));
        orderVO.setDestinationCodeName(cmCityMapper.getNameByCode(os.getDestinationCode()));
        orderVO.setPickType(os.getPickType());
        orderVO.setTakeType(os.getTakeType());
        orderVO.setPickLinkmanName(os.getPickLinkmanName());
        orderVO.setTakeLinkmanName(os.getTakeLinkmanName());
        orderVO.setPickLinkmanPhone(os.getPickLinkmanPhone());
        orderVO.setPickAddress(os.getPickAddress());
        orderVO.setTakeAddress(os.getTakeAddress());
        orderVO.setPickAreaCode(os.getPickAreaCode());
        orderVO.setTakeAreaCode(os.getTakeAreaCode());
        orderVO.setPickAreaCodeName(cmAreaMapper.getNameByCode(os.getPickAreaCode()));
        orderVO.setTakeAreaCodeName(cmAreaMapper.getNameByCode(os.getTakeAreaCode()));
        orderVO.setCarNum(orderSubList.size());
        orderVO.setHasUrgent(os.getHasUrgent());
        orderVO.setHasInsurance(os.getHasInsurance());
        if (os.getAppointPickTime() != null) {
            orderVO.setAppointPickTime(os.getAppointPickTime());
        }
        orderVO.setRemark(os.getRemark());
        orderVO.setTransportType(os.getTransportType());
        //金额
        String[] stringArray = os.getPaymentType().replace("[", "").replace("]", "").replace(" ", "").split(",");
        Integer[] integerArray = new Integer[stringArray.length];
        for (int i = 0; i < stringArray.length; i++) {
            integerArray[i] = Integer.parseInt(stringArray[i]);
        }
        orderVO.setPaymentType(integerArray);
        orderVO.setTransportFee(os.getTransportFee());
        // 需要合计的费用
        BigDecimal totalPickFee = orderSubList.stream().map(a -> a.getPickFee() == null ? BigDecimal.ZERO : a.getPickFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setPickFee(totalPickFee);
        BigDecimal totalTakeFee = orderSubList.stream().map(a -> a.getTakeFee() == null ? BigDecimal.ZERO : a.getTakeFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setTakeFee(totalTakeFee);
        BigDecimal totalKickbackFee = orderSubList.stream().map(a -> a.getKickbackFee() == null ? BigDecimal.ZERO : a.getKickbackFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setKickbackFee(totalKickbackFee);
        BigDecimal totalInvoiceFee = orderSubList.stream().map(a -> a.getInvoiceFee() == null ? BigDecimal.ZERO : a.getInvoiceFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setInvoiceFee(totalInvoiceFee);
        BigDecimal totalSpotPayFee = orderSubList.stream().map(a -> a.getSpotPayFee() == null ? BigDecimal.ZERO : a.getSpotPayFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setSpotPayFee(totalSpotPayFee);
        BigDecimal totalDeliveryPayFee = orderSubList.stream().map(a -> a.getDeliveryPayFee() == null ? BigDecimal.ZERO : a.getDeliveryPayFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setDeliveryPayFee(totalDeliveryPayFee);
        BigDecimal totalBackPayFee = orderSubList.stream().map(a -> a.getBackPayFee() == null ? BigDecimal.ZERO : a.getBackPayFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setBackPayFee(totalBackPayFee);
        BigDecimal totalSlotPayFee = orderSubList.stream().map(a -> a.getSlotPayFee() == null ? BigDecimal.ZERO : a.getSlotPayFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setSlotPayFee(totalSlotPayFee);
        // 合计费用
        BigDecimal totalFee = orderSubList.stream().map(a -> a.getTotalFee() == null ? BigDecimal.ZERO : a.getTotalFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setTotalFee(totalFee);
        orderVO.setOrderSubList(orderSubList);
        orderVO.setCreateUserName(sysUserService.getById(os.getCreateUser()).getName());
        return orderVO;
    }

    @Override
    public OrderProgressVO getSubOrderStatus(String id) {
        OrderProgressVO op = this.baseMapper.getProgressStatusById(id);
        if (op == null) {
            throw new CustomException("数据不存在");
        }
        if (op != null) {
            if (op.getStatus() == 1 || (op.getStatus() == 2 && op.getPickCarUser() == null)) {
                op.setStepStatus(0);
            } else if (op.getStatus() == 105 || (op.getStatus() == 2 && op.getPickCarUser() != null)) {
                op.setStepStatus(1);
            } else if (op.getStatus() == OrderStatusEnum.PICK_SIGNED.status) {
                op.setStepStatus(2);
            } else if (op.getStatus() == 3) {
                op.setStepStatus(3);
            } else if (op.getStatus() == 305 || op.getStatus() == OrderStatusEnum.HAS_DEPART_ORDER.status) {
                op.setStepStatus(4);
            } else if (op.getStatus() == OrderStatusEnum.FINISHED_TRANSPORT.status || (op.getStatus() == 6 && op.getTakeCarUser() == null)) {
                // 已到达
                op.setStepStatus(5);
            } else if (op.getStatus() == 505 || (op.getStatus() == 6 && op.getTakeCarUser() != null)) {
                // 已送车
                op.setStepStatus(6);
            } else {
                // 已完成
                op.setStepStatus(op.getStatus());
            }
        }
        // 操作人处理
        List<Integer> userTypeList = new ArrayList<Integer>() {{
            add(9);
            add(10);
        }};
        List<SysUser> userList = sysUserService.list(new QueryWrapper<SysUser>().lambda().eq(SysUser::getTenantId, op.getTenantId()));
        Map<String, String> map = userList.stream().collect(Collectors.toMap((user -> String.valueOf(user.getId())), SysUser::getName));
        if (StringUtils.isNotBlank(op.getCreateUser())) op.setCreateUser(map.get(op.getCreateUser()));
        if (StringUtils.isNotBlank(op.getPickCarUser())) op.setPickCarUser(map.get(op.getPickCarUser()));
        if (StringUtils.isNotBlank(op.getVerifyCarUser())) op.setVerifyCarUser(map.get(op.getVerifyCarUser()));
        if (StringUtils.isNotBlank(op.getStockUser())) op.setStockUser(map.get(op.getStockUser()));
        if (StringUtils.isNotBlank(op.getTransportUser())) op.setTransportUser(map.get(op.getTransportUser()));
        if (StringUtils.isNotBlank(op.getDeliveryUser())) op.setDeliveryUser(map.get(op.getDeliveryUser()));
        if (StringUtils.isNotBlank(op.getTakeCarUser())) op.setTakeCarUser(map.get(op.getTakeCarUser()));
        if (StringUtils.isNotBlank(op.getSignUser())) op.setSignUser(map.get(op.getSignUser()));
        return op;
    }

    @Override
    public List<OrderModifyDetail> getOrderModifyRecord(Long orderId) {
        return orderModifyDetailMapper.getByOrderId(orderId);
    }

    @Override
    public List<PkgOrderSubBase> getOrderInfos(List<Long> orderIds) {
        return this.baseMapper.getOrderInfos(orderIds);
    }

    @Override
    public void multiCancel(List<String> idList) {
        for (String id : idList) {
            this.baseMapper.cancelById(id);
            // 订单修改记录
            OrderModifyDetail orderModifyDetail = new OrderModifyDetail(
                    Long.valueOf(id), null, "cancel", "取消订单", "", "", LoginContextHolder.me().getSysLoginUserId()
            );
            orderModifyDetailMapper.insert(orderModifyDetail);
        }
    }

    @Autowired
    private FinanceSettlementMapper financeSettlementMapper;

    @Override
    public boolean checkMultiCancel(List<String> idList, StringBuilder errorMsg) {
        for (String id : idList) {
            int status = this.baseMapper.getStatusById(Long.valueOf(id));
            if (status == OrderStatusEnum.CUSTOMER_HAS_SIGN.status || status == OrderStatusEnum.HAD_WITHDRAWN.status) {
                errorMsg.append("当前订单状态不可取消");
                return false;
            }
            // 已结算的订单不可取消
            int settlementCount = financeSettlementMapper.countByOrderId(id);
            if (settlementCount > 0) {
                errorMsg.append("存在已结算的订单，不可取消");
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean checkOrderFinanceUpdate(OrderSub orderSub, StringBuilder errorMsg) {
        if (orderSub == null || orderSub.getId() == null) {
            errorMsg.append("订单参数错误");
            return false;
        }
        return true;
    }


    @Override
    public void orderFinanceUpdate(OrderSub orderSub) {
        OrderSub origin = orderSubMapper.selectById(orderSub.getId());
        List<OrderModifyDetail> orderModifyDetails = new ArrayList<>();
        Long createUserId = LoginContextHolder.me().getSysLoginUserId();
        // 运输费
        if (!BaseUtils.compareDecimal(orderSub.getTransportFee(), origin.getTransportFee())) {
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "transport_fee", "运输费", BaseUtils.objectToString(orderSub.getTransportFee()), BaseUtils.objectToString(origin.getTransportFee()), createUserId, orderSub.getRemark()));
        }
        // 保险费
        if (!BaseUtils.compareDecimal(orderSub.getInsuranceFee(), origin.getInsuranceFee())) {
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null, "insurance_fee", "保险费", BaseUtils.objectToString(orderSub.getInsuranceFee()), BaseUtils.objectToString(origin.getInsuranceFee()), createUserId, orderSub.getRemark()));
        }
        // 提车费
        if (!BaseUtils.compareDecimal(orderSub.getPickFee(), origin.getPickFee())) {
            //orderSub.setPickFee(orderVO.getPickFee());
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "pick_fee", "提车费", BaseUtils.objectToString(orderSub.getPickFee()), BaseUtils.objectToString(origin.getPickFee()), createUserId, orderSub.getRemark()));
        }
        // 送车费
        if (!BaseUtils.compareDecimal(orderSub.getTakeFee(), origin.getTakeFee())) {
            //orderSub.setTakeFee(orderVO.getTakeFee());
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "take_fee", "送车费", BaseUtils.objectToString(orderSub.getTakeFee()), BaseUtils.objectToString(origin.getTakeFee()), createUserId, orderSub.getRemark()));
        }
        if (!BaseUtils.compareStringArray(orderSub.getPaymentType(), origin.getPaymentType())) {
            //orderSub.setPaymentType(orderSub.getPaymentType());
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "payment_type", "付款方式", orderSub.getPaymentType(), origin.getPaymentType(), createUserId, orderSub.getRemark()));
        }
        // 税额
        if (!BaseUtils.compareDecimal(orderSub.getInvoiceFee(), origin.getInvoiceFee())) {
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "invoice_fee", "税额", BaseUtils.objectToString(orderSub.getInvoiceFee()), BaseUtils.objectToString(origin.getInvoiceFee()), createUserId, orderSub.getRemark()));
        }
        // 返款
        if (!BaseUtils.compareDecimal(orderSub.getKickbackFee(), origin.getKickbackFee())) {
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "kickback_fee", "返款", BaseUtils.objectToString(orderSub.getKickbackFee()), BaseUtils.objectToString(origin.getKickbackFee()), createUserId, orderSub.getRemark()));
            try {
                modifyOrderFeeDetail(orderSub.getId(),
                        FinanceTypeEnum.KICKBACK.type,
                        orderSub.getKickbackFee(),
                        origin.getKickbackFee(),
                        origin.getLinkmanId(),
                        origin.getLinkmanName(),
                        origin.getLinkmanPhone());
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }

        }
        // 现付
        if (!BaseUtils.compareDecimal(orderSub.getSpotPayFee(), origin.getSpotPayFee())) {
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "spot_pay_fee", "现付", BaseUtils.objectToString(orderSub.getSpotPayFee()), BaseUtils.objectToString(origin.getSpotPayFee()), createUserId, orderSub.getRemark()));
            try {
                modifyOrderFeeDetail(orderSub.getId(),
                        FinanceTypeEnum.SPOT.type,
                        orderSub.getSpotPayFee(),
                        origin.getSpotPayFee(),
                        origin.getLinkmanId(),
                        origin.getLinkmanName(),
                        origin.getLinkmanPhone());
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        }
        // 到付
        if (!BaseUtils.compareDecimal(orderSub.getDeliveryPayFee(), origin.getDeliveryPayFee())) {
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "delivery_pay_fee", "到付", BaseUtils.objectToString(orderSub.getDeliveryPayFee()), BaseUtils.objectToString(origin.getDeliveryPayFee()), createUserId, orderSub.getRemark()));
            try {
                modifyOrderFeeDetail(orderSub.getId(),
                        FinanceTypeEnum.DELIVERY.type,
                        orderSub.getDeliveryPayFee(),
                        origin.getDeliveryPayFee(),
                        origin.getLinkmanId(),
                        origin.getLinkmanName(),
                        origin.getLinkmanPhone());
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        }
        // 欠付
        if (!BaseUtils.compareDecimal(orderSub.getBackPayFee(), origin.getBackPayFee())) {
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "back_pay_fee", "欠付", BaseUtils.objectToString(orderSub.getBackPayFee()), BaseUtils.objectToString(origin.getBackPayFee()), createUserId, orderSub.getRemark()));
            try {
                modifyOrderFeeDetail(orderSub.getId(),
                        FinanceTypeEnum.BACK_PAY.type,
                        orderSub.getBackPayFee(),
                        origin.getBackPayFee(),
                        origin.getLinkmanId(),
                        origin.getLinkmanName(),
                        origin.getLinkmanPhone());
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        }
        // 月结
        if (!BaseUtils.compareDecimal(orderSub.getSlotPayFee(), origin.getSlotPayFee())) {
            orderModifyDetails.add(new OrderModifyDetail(orderSub.getId(), null,
                    "slot_pay_fee", "月结", BaseUtils.objectToString(orderSub.getSlotPayFee()), BaseUtils.objectToString(origin.getSlotPayFee()), createUserId, orderSub.getRemark()));
            try {
                modifyOrderFeeDetail(orderSub.getId(),
                        FinanceTypeEnum.SLOT.type,
                        orderSub.getSlotPayFee(),
                        origin.getSlotPayFee(),
                        origin.getLinkmanId(),
                        origin.getLinkmanName(),
                        origin.getLinkmanPhone());
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        }
        // 赋值
        origin.setTransportFee(orderSub.getTransportFee());
        origin.setInsuranceFee(orderSub.getInsuranceFee());
        origin.setInvoiceFee(orderSub.getInvoiceFee());
        origin.setPickFee(orderSub.getPickFee());
        origin.setTakeFee(orderSub.getTakeFee());
        origin.setPaymentType(orderSub.getPaymentType());
        origin.setSpotPayFee(orderSub.getSpotPayFee());
        origin.setDeliveryPayFee(orderSub.getDeliveryPayFee());
        origin.setBackPayFee(orderSub.getBackPayFee());
        origin.setSlotPayFee(orderSub.getSlotPayFee());
        origin.setKickbackFee(orderSub.getKickbackFee());
        // 总运费
        BigDecimal totalFee = orderSub.getTransportFee() == null ? BigDecimal.ZERO : orderSub.getTransportFee()
                .add(orderSub.getInsuranceFee() == null ? BigDecimal.ZERO : orderSub.getInsuranceFee())
                .add(orderSub.getKickbackFee() == null ? BigDecimal.ZERO : orderSub.getKickbackFee())
                .add(orderSub.getInvoiceFee() == null ? BigDecimal.ZERO : orderSub.getInvoiceFee())
                .add(orderSub.getPickFee() == null ? BigDecimal.ZERO : orderSub.getPickFee())
                .add(orderSub.getTakeFee() == null ? BigDecimal.ZERO : orderSub.getTakeFee());
        origin.setTotalFee(totalFee);
        // 更新修改版本
        Long updateVersion = SnowIdUtils.uniqueLong();
        origin.setUpdateVersion(updateVersion.toString());
        orderSubMapper.updateById(origin);
        // 订单修改明细
        if (orderModifyDetails.size() > 0) {
            for (OrderModifyDetail omd : orderModifyDetails) {
                orderModifyDetailMapper.insert(omd);
            }
        }
    }

    @Override
    public void updateOrderTransportCost(PkgTransportLevelDetailSimple orderTransport) {
        Long orderId = orderTransport.getOrderId();
        Long transportId = orderTransport.getTransportSimple().getId();
        Transport transport = transportMapper.selectOne(new QueryWrapper<Transport>().lambda().eq(Transport::getId, transportId));
        // financeDetail
        FinanceDetail fd = financeDetailMapper.getByOrderIdAndRelationId(8, orderId, transportId);
        fd.setNeedSettlement(orderTransport.getCost());
        fd.setUnSettlement(orderTransport.getCost().subtract(fd.getHasSettlement()));
        if (fd.getUnSettlement().compareTo(BigDecimal.ZERO) == 0) {
            fd.setStatus(2);
        } else {
            fd.setStatus(0);
        }
        financeDetailMapper.updateById(fd);
        // financeTransport
        FinanceTransport ft = financeTransportMapper.getByOrderIdAndTransportId(Long.valueOf(orderId), Long.valueOf(transportId));
        ft.setTransport(orderTransport.getCost());
        ft.setTransportUn(orderTransport.getCost().subtract(fd.getHasSettlement()));
        financeTransportMapper.updateById(ft);
        // transport_level_detail
        PkgTransportLevelDetailSimple tld = transportLevelDetailMapper.getPkgTransportLevelDetailSimpleByOrderIdAndTransportId(orderId, transportId);
        transportLevelDetailMapper.updateCostByOrderIdAndType(orderTransport.getCost(), orderId, transportId);
        // transport
        BigDecimal newDriverFee = orderTransport.getCost().subtract(tld.getCost()).add(transport.getDriverFee());
        transport.setDriverFee(newDriverFee);
        if (transport.getCollectionFee() != null && transport.getCollectionFee().compareTo(BigDecimal.ZERO) > 0) {
            transport.setBackReturnFee(transport.getCollectionFee().subtract(newDriverFee));
        }
        transportMapper.update(transport, new QueryWrapper<Transport>().lambda().eq(Transport::getId, transport.getId()));
        // 修改记录
        if (!BaseUtils.compareDecimal(orderTransport.getCost(), tld.getCost())) {
            OrderModifyDetail omd = new OrderModifyDetail(Long.valueOf(orderTransport.getOrderId()), Long.valueOf(orderTransport.getTransportSimple().getId()),
                    "cost", "承运费", orderTransport.getCost().toString(), tld.getCost().toString(), businessUtil.getTenantId());
            orderModifyDetailMapper.insert(omd);
        }
    }

    @Override
    public List<OrderSubExport> getOrderExportList(OrderDTO orderDTO) {
        return this.baseMapper.getOrderExportList(orderDTO);
    }

    @Override
    public void updateVin(Long id, String vin) {
        OrderSub os = this.baseMapper.selectById(id);
        this.baseMapper.updateVinById(vin, id);
        // 修改记录
        OrderModifyDetail omd = new OrderModifyDetail(id, null,
                "vin", "车架号", vin, os.getVin(), businessUtil.getTenantId());
        orderModifyDetailMapper.insert(omd);
    }


    /**
     * 订单修改财务相关字段处理
     *
     * @param orderId      orderId
     * @param financeType  类型
     * @param fee          金额
     * @param oldFee       原金额
     * @param linkmanId    结算人ID
     * @param linkmanName  结算人
     * @param linkmanPhone 结算人电话
     */
    @Transactional
    @Override
    public void modifyOrderFeeDetail(Long orderId, int financeType, BigDecimal fee, BigDecimal oldFee, Long linkmanId, String linkmanName, String linkmanPhone) throws Exception {
        FinanceDetail fd = financeDetailMapper.selectOne(new QueryWrapper<FinanceDetail>().lambda()
                .eq(FinanceDetail::getOrderId, orderId)
                .and(wrapper -> wrapper.eq(FinanceDetail::getType, financeType)));
        if (oldFee == null || oldFee.compareTo(BigDecimal.ZERO) == 0) {
            // 无 --> 有
            if (financeType != 2) {
                updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee, BigDecimal.ZERO, linkmanName, linkmanPhone);
                FinanceDetail fd1 = new FinanceDetail();
                fd1.setOrderId(Long.valueOf(orderId));
                fd1.setSettlementUserId(Long.valueOf(linkmanId));
                fd1.setSettlementUser(linkmanName);
                fd1.setSettlementPhone(linkmanPhone);
                fd1.setType(financeType);
                fd1.setNeedSettlement(fee);
                fd1.setHasSettlement(BigDecimal.ZERO);
                fd1.setUnSettlement(fee);
                financeDetailMapper.insert(fd1);
            } else {
                // 到付
                Map<String, String> map = getDeliveryPaySettlementUser(orderId);
                if (map.get("name") != null) {
                    updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee, BigDecimal.ZERO, map.get("name"), map.get("phone"));
                    FinanceDetail fd1 = new FinanceDetail();
                    fd1.setOrderId(orderId);
                    fd1.setSettlementUserId(Long.valueOf(map.get("settlementId")));
                    fd1.setSettlementUser(map.get("name"));
                    fd1.setSettlementPhone(map.get("phone"));
                    fd1.setType(financeType);
                    fd1.setNeedSettlement(fee);
                    fd1.setHasSettlement(BigDecimal.ZERO);
                    fd1.setUnSettlement(fee);
                    financeDetailMapper.insert(fd1);
                } else {
                    updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee, BigDecimal.ZERO, "", "");
                }
            }

        } else if (fee == null || fee.compareTo(BigDecimal.ZERO) == 0) {
            // 有 --> 无
            try {
                if (fd != null) {
                    if (fd.getStatus() == 2) {
                        // 已经结算不可修改，不可删除
                        throw new CustomException("已经结算不可修改");
                    } else if (fd.getStatus() == 1) {
                        // 部分结算
                        throw new CustomException("已经结算不可修改");
                    } else {
                        // 未结算的，删除对应费用信息
                        updateOrderFinanceInfo(orderId.toString(), financeType, null, null, null, "", "");
                        financeDetailMapper.deleteById(fd.getId());
                    }
                } else {
                    updateOrderFinanceInfo(orderId.toString(), financeType, null, null, null, "", "");
                }
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        } else {
            // 修改金额
            try {
                if (fd != null) {
                    if (fd.getHasSettlement().compareTo(BigDecimal.ZERO) > 0 && fee.compareTo(fd.getHasSettlement()) < 0) {
                        // 不可改为小于已经结算的金额
                        throw new CustomException("不可改为小于已经结算的金额");
                    } else {
                        if (financeType == 2) {
                            financeMapper.updateDeliveryFeeOnly(orderId.toString(), fee.subtract(fd.getHasSettlement()), fd.getHasSettlement());
                        } else {
                            updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee.subtract(fd.getHasSettlement()), fd.getHasSettlement(), linkmanName, linkmanPhone);
                        }
                        fd.setNeedSettlement(fee);
                        //fd.setHasSettlement(BigDecimal.ZERO);
                        fd.setUnSettlement(fee.subtract(fd.getHasSettlement()));
                        if (fd.getUnSettlement().compareTo(BigDecimal.ZERO) == 0) {
                            fd.setStatus(2);
                        } else {
                            fd.setStatus(0);
                        }
                        financeDetailMapper.updateById(fd);
                    }
                } else {
                    // 到付金额未发运，未签收之前可能是null，只更新finance表即可
                    Map<String, String> map = getDeliveryPaySettlementUser(orderId);
                    updateOrderFinanceInfo(orderId.toString(), financeType, fee, fee, BigDecimal.ZERO, map.get("name"), map.get("phone"));
                }

            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        }
    }


/*    @Override
    public OrderProgressVO getSubOrderStatus(String id) {
        OrderProgressVO op = this.baseMapper.getProgressStatusById(id);
        if (op != null) {
            if (op.getStatus() == 1 || (op.getStatus() == 2 && op.getPickCarUser() == null)) {
                op.setStepStatus(0);
            } else if (op.getStatus() == 105 || (op.getStatus() == 2 && op.getPickCarUser() != null)) {
                op.setStepStatus(1);
            } else if (op.getStatus() == OrderStatusEnum.PICK_SIGNED.status) {
                op.setStepStatus(2);
            } else if (op.getStatus() == 3) {
                op.setStepStatus(3);
            } else if (op.getStatus() == 305 || op.getStatus() == OrderStatusEnum.HAS_DEPART_ORDER.status) {
                op.setStepStatus(4);
            } else if (op.getStatus() == OrderStatusEnum.FINISHED_TRANSPORT.status || (op.getStatus() == 6 && op.getTakeCarUser() == null)){
                // 已到达
                op.setStepStatus(5);
            } else if (op.getStatus() == 505 || (op.getStatus() == 6 && op.getTakeCarUser() != null)) {
                // 已送车
                op.setStepStatus(6);
            } else {
                // 已完成
                op.setStepStatus(op.getStatus());
            }
        }
        // 操作人处理
        List<Integer> userTypeList = new ArrayList<Integer>() {{
            add(9);
            add(10);
        }};
        List<User> userList = userMapper.selectList(new QueryWrapper<User>().lambda().notIn(User::getType, userTypeList));
        Map<String, String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getNickName));
        if (StringUtils.isNotBlank(op.getCreateUser())) op.setCreateUser(map.get(op.getCreateUser()));
        if (StringUtils.isNotBlank(op.getPickCarUser())) op.setPickCarUser(map.get(op.getPickCarUser()));
        if (StringUtils.isNotBlank(op.getVerifyCarUser())) op.setVerifyCarUser(map.get(op.getVerifyCarUser()));
        if (StringUtils.isNotBlank(op.getStockUser())) op.setStockUser(map.get(op.getStockUser()));
        if (StringUtils.isNotBlank(op.getTransportUser())) op.setTransportUser(map.get(op.getTransportUser()));
        if (StringUtils.isNotBlank(op.getDeliveryUser())) op.setDeliveryUser(map.get(op.getDeliveryUser()));
        if (StringUtils.isNotBlank(op.getTakeCarUser())) op.setTakeCarUser(map.get(op.getTakeCarUser()));
        if (StringUtils.isNotBlank(op.getSignUser())) op.setSignUser(map.get(op.getSignUser()));
        return op;
    }*/


    private int getMaxStatusByOrderIdList(List<Long> orderIdList) {
        int result = 100;
        for (Long id : orderIdList) {
            int stauts = this.baseMapper.getStatusById(id);
            stauts = stauts > 100 ? stauts : stauts * 100;
            if (stauts > result) {
                result = stauts;
            }
        }
        return result;
    }

    private void bandAppOrder(String orderId, String appOrderId) {
        //appOrderMapper.updateOrderId(orderId, appOrderId);
        //appOrderMapper.updateStatus(appOrderId, 1);
    }


    /**
     * 更新客户最后一次下单时间
     */
    private void dualCustomerInfo(OrderVO orderVO) {
        // 更新客户最后一次下单时间
        CmLinkman linkman = linkmanMapper.selectById(orderVO.getLinkmanId());
        linkmanMapper.updateLastOrderTime(linkman.getId());
        companyMapper.updateLastOrderTime(linkman.getCompanyId());
    }

    //todo 网点人员奖金明细处理
    private void addOrderBonus(OrderSub os) {
        // 网点人员奖金明细处理
        producer.sendBonus(BonusTypeEnum.CREATE_ORDER.type, os.getId(), LoginContextHolder.me().getSysLoginUserId(), null);
       /* SysLoginUser user = LoginContextHolder.me().getSysLoginUser();
        if (user.getType() == UserTypeEnum.DISPATCHER.type && isSiteSelfOrder(os.getLinkmanId(), user.getId())) {
            // 插入提成表，状态为未生效
            OrderRoyalty orderRoyalty = new OrderRoyalty();
            orderRoyalty.setOrderId(os.getId());
            orderRoyalty.setGrossFee(BigDecimal.ZERO);
            orderRoyalty.setRoyaltyFee(BigDecimal.ZERO);
            orderRoyalty.setUserId(LoginContextHolder.me().getSysLoginUserId());
            orderRoyalty.setStatus(1);
            orderRoyaltyMapper.insert(orderRoyalty);
        }*/
    }

    protected void addCompanyOrder(OrderSub orderSub, Long tenantId) {
        CmLinkman linkman = linkmanMapper.selectById(orderSub.getLinkmanId());
        CmCompanyOrder companyOrder = new CmCompanyOrder();
        companyOrder.setId(SnowIdUtils.uniqueLong());
        if (linkman != null) {
            companyOrder.setCompanyId(linkman.getCompanyId());
        }
        companyOrder.setLinkmanId(orderSub.getLinkmanId());
        companyOrder.setOrderId(orderSub.getId());
        companyOrder.setType(1);
        companyOrder.setTenantId(tenantId);
        companyOrder.setFee(orderSub.getTotalFee());
        companyOrderMapper.insert(companyOrder);
    }

    private void dealFinanceCollectionData(OrderSub orderSub, Integer hasUpdate, Long tenantId) {
        Finance finance = new Finance();
        if (hasUpdate == 0) {
            finance.setId(SnowIdUtils.uniqueLong());
        }
        finance.setTenantId(tenantId);
        finance.setOrderId(orderSub.getId());
        if (orderSub.getSpotPayFee() != null && orderSub.getSpotPayFee().compareTo(BigDecimal.ZERO) != 0) {
            // 现付未收
            finance.setSpotUn(orderSub.getSpotPayFee());
            finance.setSpotNeed(orderSub.getSpotPayFee());
            // 现付已收
            finance.setSpotHas(BigDecimal.ZERO);
            // 现付结算人
            finance.setSpotSettlementName(orderSub.getLinkmanName());
            // 现付结算人电话
            finance.setSpotSettlementPhone(orderSub.getLinkmanPhone());
            dealFinanceDetail(orderSub, FinanceTypeEnum.SPOT.type, tenantId);
        }
        if (orderSub.getDeliveryPayFee() != null && orderSub.getDeliveryPayFee().compareTo(BigDecimal.ZERO) != 0) {
            // 到付已收
            finance.setDeliveryHas(BigDecimal.ZERO);
            // 到付未收
            finance.setDeliveryUn(orderSub.getDeliveryPayFee());
            finance.setDeliveryNeed(orderSub.getDeliveryPayFee());
            // 到付结算人已经结算电话需等到发运完成才能确定
        }
        if (orderSub.getBackPayFee() != null && orderSub.getBackPayFee().compareTo(BigDecimal.ZERO) != 0) {
            // 欠付已收
            finance.setBackHas(BigDecimal.ZERO);
            // 欠付未收
            finance.setBackUn(orderSub.getBackPayFee());
            finance.setBackUn(orderSub.getBackPayFee());
            // 欠付结算人
            finance.setBackSettlementName(orderSub.getLinkmanName());
            finance.setBackSettlementPhone(orderSub.getLinkmanPhone());
            dealFinanceDetail(orderSub, FinanceTypeEnum.BACK_PAY.type, tenantId);
        }
        // 月结
        if (orderSub.getSlotPayFee() != null && orderSub.getSlotPayFee().compareTo(BigDecimal.ZERO) != 0) {
            finance.setSlotHas(BigDecimal.ZERO);
            finance.setSlotUn(orderSub.getSlotPayFee());
            finance.setSlotNeed(orderSub.getSlotPayFee());
            finance.setSlotSettlementName(orderSub.getLinkmanName());
            finance.setSlotSettlementPhone(orderSub.getLinkmanPhone());
            dealFinanceDetail(orderSub, FinanceTypeEnum.SLOT.type, tenantId);
        }
        // 回扣
        if (orderSub.getKickbackFee() != null && orderSub.getKickbackFee().compareTo(BigDecimal.ZERO) != 0) {
            finance.setKickbackHas(BigDecimal.ZERO);
            finance.setKickbackUn(orderSub.getKickbackFee());
            finance.setKickbackSettlementName(orderSub.getLinkmanName());
            finance.setKickbackSettlementPhone(orderSub.getLinkmanPhone());
            dealFinanceDetail(orderSub, FinanceTypeEnum.KICKBACK.type, tenantId);
        }
        if (hasUpdate == 1) {
            financeMapper.update(finance, new QueryWrapper<Finance>().lambda().eq(Finance::getOrderId, orderSub.getId()));
        } else {
            financeMapper.insert(finance);
        }
    }

    private void dealFinanceDetail(OrderSub orderSub, Integer financeType, Long tenantId) {
        FinanceDetail fd = new FinanceDetail();
        fd.setId(SnowIdUtils.uniqueLong());
        fd.setOrderId(orderSub.getId());
        fd.setType(financeType);
        fd.setTenantId(tenantId);
        if (financeType == FinanceTypeEnum.SPOT.type) {
            fd.setUnSettlement(orderSub.getSpotPayFee());
            fd.setNeedSettlement(orderSub.getSpotPayFee());
        } else if (financeType == FinanceTypeEnum.BACK_PAY.type) {
            fd.setUnSettlement(orderSub.getBackPayFee());
            fd.setNeedSettlement(orderSub.getBackPayFee());
        } else if (financeType == FinanceTypeEnum.SLOT.type) {
            fd.setUnSettlement(orderSub.getSlotPayFee());
            fd.setNeedSettlement(orderSub.getSlotPayFee());
        } else if (financeType == FinanceTypeEnum.KICKBACK.type) {
            fd.setUnSettlement(orderSub.getKickbackFee());
            fd.setNeedSettlement(orderSub.getKickbackFee());
        }
        fd.setHasSettlement(BigDecimal.ZERO);
        fd.setSettlementUser(orderSub.getLinkmanName());
        fd.setSettlementUserId(orderSub.getLinkmanId());
        fd.setSettlementPhone(orderSub.getLinkmanPhone());
        financeDetailMapper.insert(fd);
    }

    /**
     * 获取子订单的总费用
     * 现付+到付+欠付+月结
     *
     * @param os
     * @return
     */
    private BigDecimal getOrderSubTotalFee(OrderSub os) {
        BigDecimal totalFee = BigDecimal.ZERO;
        if (os == null) {
            return totalFee;
        }
        totalFee = totalFee.add(os.getSpotPayFee() == null ? BigDecimal.ZERO : os.getSpotPayFee())
                .add(os.getDeliveryPayFee() == null ? BigDecimal.ZERO : os.getDeliveryPayFee())
                .add(os.getBackPayFee() == null ? BigDecimal.ZERO : os.getBackPayFee())
                .add(os.getSlotPayFee() == null ? BigDecimal.ZERO : os.getSlotPayFee());
        return totalFee;
    }

    private String createOrderSubNo(long orderNo, int size, int index) {
        return "" + orderNo + "-" + size + "-" + index;
    }


    /*private OrderVO getOrderVOByOrderIdList(List<Long> idList) {
        List<OrderSub> orderSubList = this.baseMapper.selectList(new QueryWrapper<OrderSub>().lambda()
                .in(OrderSub::getId, idList));
        OrderSub os = orderSubList.get(0);
        OrderVO orderVO = new OrderVO();
        orderVO.setId(os.getOrderId());
        orderVO.setCompanyName(os.getCompanyName());
        orderVO.setLinkmanId(os.getLinkmanId());
        orderVO.setCanSlotPay(linkmanMapper.getNatureById(os.getLinkmanId()));
        orderVO.setLinkmanName(os.getLinkmanName());
        orderVO.setLinkmanPhone(os.getLinkmanPhone());
        orderVO.setConsigneeName(os.getConsigneeName());
        orderVO.setConsigneePhone(os.getConsigneePhone());
        orderVO.setStartCode(os.getStartCode());
        orderVO.setDestinationCode(os.getDestinationCode());
        orderVO.setPickType(os.getPickType());
        orderVO.setTakeType(os.getTakeType());
        orderVO.setPickLinkmanName(os.getPickLinkmanName());
        orderVO.setTakeLinkmanName(os.getTakeLinkmanName());
        orderVO.setPickLinkmanPhone(os.getPickLinkmanPhone());
        orderVO.setPickAddress(os.getPickAddress());
        orderVO.setTakeAddress(os.getTakeAddress());
        orderVO.setPickAreaCode(os.getPickAreaCode());
        orderVO.setTakeAreaCode(os.getTakeAreaCode());
        orderVO.setCarNum(orderSubList.size());
        orderVO.setHasUrgent(os.getHasUrgent());
        orderVO.setHasInsurance(os.getHasInsurance());
        if (os.getAppointPickTime()!=null) {
            orderVO.setAppointPickTime(os.getAppointPickTime());
        }
        orderVO.setRemark(os.getRemark());
        orderVO.setTransportType(os.getTransportType());
        //金额
        orderVO.setPaymentType(os.getPaymentType());
        orderVO.setTransportFee(os.getTransportFee());
        // 需要合计的费用
        BigDecimal totalPickFee = orderSubList.stream().map(a -> a.getPickFee() == null ? BigDecimal.ZERO : a.getPickFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setPickFee(totalPickFee.compareTo(BigDecimal.ZERO) > 0 ? totalPickFee : null);
        BigDecimal totalTakeFee = orderSubList.stream().map(a -> a.getTakeFee() == null ? BigDecimal.ZERO : a.getTakeFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setTakeFee(totalTakeFee.compareTo(BigDecimal.ZERO) > 0 ? totalTakeFee : null);
        BigDecimal totalKickbackFee = orderSubList.stream().map(a -> a.getKickbackFee() == null ? BigDecimal.ZERO : a.getKickbackFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setKickbackFee(totalKickbackFee.compareTo(BigDecimal.ZERO) > 0 ? totalKickbackFee : null);
        BigDecimal totalInvoiceFee = orderSubList.stream().map(a -> a.getInvoiceFee() == null ? BigDecimal.ZERO : a.getInvoiceFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setInvoiceFee(totalInvoiceFee.compareTo(BigDecimal.ZERO) > 0 ? totalInvoiceFee : null);
        BigDecimal totalSpotPayFee = orderSubList.stream().map(a -> a.getSpotPayFee() == null ? BigDecimal.ZERO : a.getSpotPayFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setSpotPayFee(totalSpotPayFee.compareTo(BigDecimal.ZERO) > 0 ? totalSpotPayFee : null);
        BigDecimal totalDeliveryPayFee = orderSubList.stream().map(a -> a.getDeliveryPayFee() == null ? BigDecimal.ZERO : a.getDeliveryPayFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setDeliveryPayFee(totalDeliveryPayFee.compareTo(BigDecimal.ZERO) > 0 ? totalDeliveryPayFee : null);
        BigDecimal totalBackPayFee = orderSubList.stream().map(a -> a.getBackPayFee() == null ? BigDecimal.ZERO : a.getBackPayFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setBackPayFee(totalBackPayFee.compareTo(BigDecimal.ZERO) > 0 ? totalBackPayFee : null);
        BigDecimal totalSlotPayFee = orderSubList.stream().map(a -> a.getSlotPayFee() == null ? BigDecimal.ZERO : a.getSlotPayFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setSlotPayFee(totalSlotPayFee.compareTo(BigDecimal.ZERO) > 0 ? totalSlotPayFee : null);
        // 合计费用
        BigDecimal totalFee = orderSubList.stream().map(a -> a.getTotalFee() == null ? BigDecimal.ZERO : a.getTotalFee()).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderVO.setTotalFee(totalFee.compareTo(BigDecimal.ZERO) > 0 ? totalFee : BigDecimal.ZERO);
        orderVO.setOrderSubList(orderSubList);
        orderVO.setCreateUserName(userMapper.selectById(os.getCreateUser()).getNickName());
        return orderVO;
    }*/


    /**
     * 获取子订单
     *
     * @author yujie
     * @since 2023/05/09 17:16
     */
    private OrderSub queryOrderSub(OrderSubParam orderSubParam) {
        OrderSub orderSub = this.getById(orderSubParam.getId());
        if (ObjectUtil.isEmpty(orderSub)) {
            throw new ServiceException(OrderSubExceptionEnum.NOT_EXISTED);
        }
        return orderSub;
    }
}
